.NET 幫助

將字串解析為整數 C#(開發人員如何操作)

轉換資料類型 是程式設計中的基本概念,而在使用C#程式設計時,將數字的字串表示轉換為整數是最常見的任務之一。 此過程在許多應用中非常有用,特別是在需要將用戶輸入或外部來源的數據轉換為數字格式以進行計算或其他操作時。

在本教程中,我們將探討 C# 提供的不同方法來將字串轉換為整數。 我們還將探索IronPDF 庫主頁

將字串變數轉換為整數的基本知識

Convert.ToInt32Int32.Parse 方法是 C# 中將字串值轉換為整數值的標準工具。 這些功能旨在解釋輸入字串的數值並將其轉換為整數。 然而,如果字符串格式不正確,這些方法可能會拋出異常,這使得異常處理成為使用這些工具的一個重要方面。

使用 Int32.Parse 方法

Int32.Parse 方法將有效的數字字串直接轉換為整數。 它要求字符串必須是有效的數字格式; 否則,將引發FormatException。 如果您確定該字串是有效數字,這種方法就很簡單。 例如:

public static string inputString = "123";
public static int result = int.Parse(inputString);
Console.WriteLine(result);
public static string inputString = "123";
public static int result = int.Parse(inputString);
Console.WriteLine(result);
Public Shared inputString As String = "123"
Public Shared result As Integer = Integer.Parse(inputString)
Console.WriteLine(result)
$vbLabelText   $csharpLabel

在上述代碼中,inputString 包含一個有效的數字,而 Parse 方法將其轉換為整數 123。然而,如果 inputString 包含非數字字符或是一個空字符串,使用 Parse 會導致 FormatExceptionArgumentNullException

使用 Convert.ToInt32 方法

將字串轉換為整數的另一個轉換類別是Convert.ToInt32。 此方法類似於Int32.Parse,但它提供了更多的靈活性。 了解如何在 C# 中有效地將字串轉換為整數,不僅能開啟許多資料操作的可能性,還能確保應用程式的強健性能。 它透過返回預設值零來處理空值和空字串,從而避免拋出異常。 以下是使用方法:

public static string inputString = null;
public static int result = Convert.ToInt32(inputString);
Console.WriteLine(result);
public static string inputString = null;
public static int result = Convert.ToInt32(inputString);
Console.WriteLine(result);
Public Shared inputString As String = Nothing
Public Shared result As Integer = Convert.ToInt32(inputString)
Console.WriteLine(result)
$vbLabelText   $csharpLabel

這個方法將把inputString轉換為0而不會拋出異常,這使得對於可能沒有正確初始化的變量來說更安全。

進階技術:Int32.TryParse

為了更好地控制轉換過程,特別是在處理可能不可靠的用戶輸入時,Int32.TryParse 是首選方法。 此方法嘗試解析數字字串,並返回一個布林值,指示TryParse方法是否成功將字串轉換為整數。 它使用 out 參數來返回轉換後的整數。

使用 Int32.TryParse 的示例

以下是如何使用Int32.TryParse方法安全地將字串輸入轉換為整數值,並優雅地處理任何無效的字串輸入:

string inputString = "abc123";
int num;
bool conversionSucceeded = int.TryParse(inputString, out num);
if (conversionSucceeded)
{
    Console.WriteLine("Successfully parsed: " + num);
}
else
{
    Console.WriteLine("Conversion failed. Provided string is not a valid integer.");
}
string inputString = "abc123";
int num;
bool conversionSucceeded = int.TryParse(inputString, out num);
if (conversionSucceeded)
{
    Console.WriteLine("Successfully parsed: " + num);
}
else
{
    Console.WriteLine("Conversion failed. Provided string is not a valid integer.");
}
Dim inputString As String = "abc123"
Dim num As Integer = Nothing
Dim conversionSucceeded As Boolean = Integer.TryParse(inputString, num)
If conversionSucceeded Then
	Console.WriteLine("Successfully parsed: " & num)
Else
	Console.WriteLine("Conversion failed. Provided string is not a valid integer.")
End If
$vbLabelText   $csharpLabel

在此範例中,Int32.TryParse 返回 false,因為 inputString 不是有效的整數。 out 參數 num 保持為 0,程式會在不拋出任何例外的情況下通知使用者轉換失敗。

IronPDF 庫介紹

IronPDF 概覽部分 是一個強大的 C# 函式庫,專為使用 .NET 框架的開發人員簡化 PDF 操作而設計。 它允許直接從 HTML、CSS、JavaScript 和圖像創建、編輯和管理PDF 文件。 IronPDF 的主要功能是能將 HTML 內容直接轉換成 PDF。

這包括轉換整個網頁或 HTML 字串,使其具有很高的靈活性。 IronPDF 被設計成既強大又易於整合,並支持各種開發環境。

範例程式碼

這是一個簡單的範例,結合使用 IronPDF 進行 PDF 生成,並使用 C# 代碼將字串解析為整數並顯示在 PDF 中。 此範例假設您想要將一個數字字串轉換為整數,然後使用IronPDF將整數打印在PDF文件中。

using IronPdf;
using System;
class Program
{
    static void Main(string[] args)
    {
        License.LicenseKey = "Your-License-Key";
        // Create a new PDF document
        var pdf = new ChromePdfRenderer();
        // Sample string that represents an integer
        string numberString = "12345";
        // Parse the string into an integer
        int number;
        bool result = Int32.TryParse(numberString, out number);
        if (result)
        {
            // Create HTML content including the parsed number
            string htmlContent = $"<h1>The number is: {number}</h1>";
            // Generate a PDF from the HTML string
            var document = pdf.RenderHtmlAsPdf(htmlContent);
            // Save the PDF to a file
            document.SaveAs("Output.pdf");
            Console.WriteLine("PDF generated successfully with the number included.");
        }
        else
        {
            Console.WriteLine("The string could not be parsed into an integer.");
        }
    }
}
using IronPdf;
using System;
class Program
{
    static void Main(string[] args)
    {
        License.LicenseKey = "Your-License-Key";
        // Create a new PDF document
        var pdf = new ChromePdfRenderer();
        // Sample string that represents an integer
        string numberString = "12345";
        // Parse the string into an integer
        int number;
        bool result = Int32.TryParse(numberString, out number);
        if (result)
        {
            // Create HTML content including the parsed number
            string htmlContent = $"<h1>The number is: {number}</h1>";
            // Generate a PDF from the HTML string
            var document = pdf.RenderHtmlAsPdf(htmlContent);
            // Save the PDF to a file
            document.SaveAs("Output.pdf");
            Console.WriteLine("PDF generated successfully with the number included.");
        }
        else
        {
            Console.WriteLine("The string could not be parsed into an integer.");
        }
    }
}
Imports IronPdf
Imports System
Friend Class Program
	Shared Sub Main(ByVal args() As String)
		License.LicenseKey = "Your-License-Key"
		' Create a new PDF document
		Dim pdf = New ChromePdfRenderer()
		' Sample string that represents an integer
		Dim numberString As String = "12345"
		' Parse the string into an integer
		Dim number As Integer = Nothing
		Dim result As Boolean = Int32.TryParse(numberString, number)
		If result Then
			' Create HTML content including the parsed number
			Dim htmlContent As String = $"<h1>The number is: {number}</h1>"
			' Generate a PDF from the HTML string
			Dim document = pdf.RenderHtmlAsPdf(htmlContent)
			' Save the PDF to a file
			document.SaveAs("Output.pdf")
			Console.WriteLine("PDF generated successfully with the number included.")
		Else
			Console.WriteLine("The string could not be parsed into an integer.")
		End If
	End Sub
End Class
$vbLabelText   $csharpLabel

將字串解析為整數 C#(開發人員如何運作):圖 1 - 來自前述代碼範例的輸出 PDF

結論

在 C# 程式設計中,將字串轉換為整數是一個常見需求,特別是在處理來自用戶或外部來源的數據輸入時。 理解Int32.ParseConvert.ToInt32TryParse方法之間的差異對於撰寫穩健且抗錯誤的代碼至關重要。

通過有效使用這些方法,您可以確保您的應用程式能夠處理各種輸入格式,並對無效數據做出合適的響應。 探索 IronPDF 的免費試用許可證,讓用戶在購買前探索其功能。 對於希望長期將 IronPDF 集成到他們專案中的人,IronPDF 授權選項 起價為 $749。

Chipego
奇佩戈·卡林达
軟體工程師
Chipego 擁有天生的傾聽技能,這幫助他理解客戶問題,並提供智能解決方案。他在獲得信息技術理學學士學位後,于 2023 年加入 Iron Software 團隊。IronPDF 和 IronOCR 是 Chipego 專注的兩個產品,但隨著他每天找到新的方法來支持客戶,他對所有產品的了解也在不斷增長。他喜歡在 Iron Software 的協作生活,公司內的團隊成員從各自不同的經歷中共同努力,創造出有效的創新解決方案。當 Chipego 離開辦公桌時,他常常享受讀好書或踢足球的樂趣。
< 上一頁
Rebus .NET Core 示例(開發人員使用方式)
下一個 >
C# 呼叫基底建構函式(開發者如何運作)