.NET 幫助

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

發佈 2024年6月6日
分享:

轉換數據類型 在程式設計中,是一個基本概念,而在使用 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)
VB   C#

在上述代碼中,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)
VB   C#

此方法將 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
VB   C#

在這個例子中,Int32.TryParse 返回 false,因為 inputString 不是有效的整數。輸出參數 num 保持為 0,程序在不拋出任何異常的情況下通知用戶轉換失敗。

IronPDF 庫簡介

IronPDF 是一個強大的C#庫,旨在簡化使用.NET框架的開發人員的PDF處理。它允許創建、編輯和管理 直接從 HTML 生成 PDF 文件, CSS, JavaScript, 和圖片。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
VB   C#

將字串解析為整數 C#(開發人員如何使用):圖 1 - 從先前的代碼範例輸出的 PDF

結論

在 C# 程式設計中,將字串轉換成整數是一個常見的需求,尤其是在處理來自用戶或外部來源的數據輸入時。理解 Int32.ParseConvert.ToInt32TryParse 方法之間的差異對於編寫健壯且抗錯誤的代碼是必不可少的。

通過有效地使用這些方法,您可以確保您的應用程式能夠處理各種輸入格式,並對無效數據作出優雅的回應。 IronPDF 供用戶在購買前探索其功能。對於那些希望長期將IronPDF整合到其項目中的人來說, 授權 從 $749 開始。

< 上一頁
Rebus .NET Core 示例(開發人員使用方式)
下一個 >
C# 呼叫基底建構函式(開發者如何運作)

準備開始了嗎? 版本: 2024.10 剛剛發布

免費 NuGet 下載 總下載次數: 10,993,239 查看許可證 >