跳過到頁腳內容
.NET幫助

Parse String to Int C#(對於開發者的運行原理)

轉換資料類型是程式設計中的基本概念,使用 C# 程式設計時,將數字的字串表示轉換為整數是最常見的工作之一。 在許多應用程式中,使用者的輸入或來自外部來源的資料需要轉換成數值格式,以便進行計算或其他作業,此流程在這些應用程式中非常有用。

在本教程中,我們將探討 C# 提供的不同方法,以將字串轉換為整數。 我們也將探討 IronPDF 圖書館首頁

將字串變數轉換為 Int 的基礎知識

Convert.ToInt32Int32.Parse 方法是 C# 中將字串值轉換為整數值的標準工具。 這些函式的設計目的在於詮釋輸入字串的數值,並將其轉換為 int。 然而,如果字串格式不正確,這些方法可能會產生異常,因此異常處理是使用這些工具的重要一環。

使用 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 但提供了多一點的彈性。 它透過返回預設值 0 來處理 null 和空字串,避免產生異常。 以下是您的使用方式:

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 並非有效的整數。 輸出參數 num 仍為 0,程式會告知使用者轉換失敗,但不會拋出任何異常。

IronPDF 圖書館簡介

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

這包括轉換整個網頁或 HTML 字串,使其具有高度彈性。 IronPDF 的設計既強大又容易整合,並支援各種開發環境。

程式碼範例

以下是一個簡單的範例,結合 IronPDF 來產生 PDF,並使用 C# 程式碼將字串解析為整數,並顯示在 PDF 內。 本範例假設您要取得數值字串,將其轉換為整數,然後在 PDF 文件中使用 IronPDF 列印整數。

using IronPdf;
using System;

class Program
{
    static void Main(string[] args)
    {
        // License your IronPdf installation
        License.LicenseKey = "Your-License-Key";

        // Create a new PDF document
        var pdf = new ChromePdfRenderer();

        // Sample string that represents an integer
        string numberString = "12345";

        // Attempt to 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 your IronPdf installation
        License.LicenseKey = "Your-License-Key";

        // Create a new PDF document
        var pdf = new ChromePdfRenderer();

        // Sample string that represents an integer
        string numberString = "12345";

        // Attempt to 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 your IronPdf installation
		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"

		' Attempt to 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

Parse String to Int C# (How It Works For Developers):圖 1 - 上一個程式碼範例輸出的 PDF

結論

在 C# 程式設計中,將字串轉換為整數是一項常見的需求,尤其是在處理來自使用者或外部來源的資料輸入時。 了解 Int32.Parse, Convert.ToInt32, 和 TryParse 方法之間的差異對於編寫健壯且抗錯的程式碼是非常重要的。

透過有效使用這些方法,您可以確保您的應用程式能夠處理各種輸入格式,並對無效資料作出優雅的回應。 探索 IronPDF 的免費試用授權,在承諾購買之前探索其功能。 對於那些希望將 IronPDF 長期整合到其專案中的人,IronPDF 授權選項從 $799 開始。

常見問題解答

如何在 C# 中將字串轉換為整數?

在 C# 中,您可以使用 Convert.ToInt32Int32.ParseInt32.TryParse 等方法將字串轉換為整數。每個方法都有其優點,其中 Int32.TryParse 是處理無異常的無效輸入的理想方法。

在 C# 中,將使用者輸入字串轉換為整數的最佳方法是什麼?

建議使用 Int32.TryParse 方法在 C# 中將使用者輸入字串轉換為整數,因為此方法會提供表示成功或失敗的布林結果,允許程式優雅地處理無效輸入,而不會拋出異常。

在 C# 中,Convert.ToInt32 方法如何處理 null 或空字串?

C# 中的 Convert.ToInt32 方法透過返回預設的整數值 0 來處理 null 或空字串,從而避免因無效輸入而可能發生的異常。

在 C# 中使用 Int32.Parse 時,為何要進行異常處理?

在使用 Int32.Parse 時,異常處理是必要的,因為如果輸入字串不是有效的數值格式或為空,它會拋出 FormatException ,如果處理不當,可能會中斷程式流程。

IronPDF 可以用來將解析的整數整合到 PDF 文件中嗎?

是的,IronPDF 可用於將 HTML 內容(可能包括解析後的整數)直接轉換為 PDF 文件,方便格式化數值資料的顯示與散佈。

在 C# 中將字串轉換為整數的實際應用是什麼?

實際應用是將用戶輸入或外部資料轉換成數字格式,以便在應用程式中進行計算或處理,例如財務計算或統計分析。

IronPDF 如何協助在 C# 應用程式中建立 PDF?

IronPDF 是一個 C# 函式庫,可協助 PDF 製作,讓開發人員從 HTML、CSS、JavaScript 和影像中產生、編輯和管理 PDF,使其成為將網頁內容整合至 PDF 文件的理想工具。

在 C# 中使用 Int32.TryParse 進行整數轉換有什麼好處?

Int32.TryParse 提供了不會針對無效輸入拋出異常的優點。它提供了一個表示轉換成功的布林值,允許開發人員以可控制的方式處理錯誤。

Jacob Mellor, Team Iron 首席技术官
首席技术官

Jacob Mellor 是 Iron Software 的首席技術官,作為 C# PDF 技術的先鋒工程師。作為 Iron Software 核心代碼的原作者,他自開始以來塑造了公司產品架構,與 CEO Cameron Rimington 一起將其轉變為一家擁有超過 50 名員工的公司,為 NASA、特斯拉 和 全世界政府機構服務。

Jacob 持有曼徹斯特大學土木工程一級榮譽学士工程學位(BEng) (1998-2001)。他於 1999 年在倫敦開設了他的第一家軟件公司,並於 2005 年製作了他的首個 .NET 組件,專注於解決 Microsoft 生態系統內的複雜問題。

他的旗艦產品 IronPDF & Iron Suite .NET 庫在全球 NuGet 被安裝超過 3000 萬次,其基礎代碼繼續為世界各地的開發工具提供動力。擁有 25 年的商業經驗和 41 年的編碼專業知識,Jacob 仍專注於推動企業級 C#、Java 及 Python PDF 技術的創新,同時指導新一代技術領袖。