.NET 幫助

Parseint C#(對開發人員的工作原理)

發佈 2025年1月14日
分享:

在使用 C# 處理資料時,開發人員經常需要將數字的文本表示轉換為整數。 這個被稱為「解析整數」的任務,對於各種應用來說都是至關重要的,從處理使用者輸入到從像PDF這樣的文件中提取數據。 雖然 C# 提供了強大的方法來解析整數在處理像 PDF 中發現的非結構化或半結構化數據時,過程可能會變得更複雜。

這就是IronPDF,這是一個為 .NET 開發人員設計的強大 PDF 函式庫,發揮了作用。 使用 IronPDF,您可以從 PDF 中提取文本,並利用 C# 的解析功能將這些文本轉換為可用的數據。 無論您是在分析發票、報告還是表格,結合 C# 的解析工具與 IronPDF 可以簡化 PDF 資料的處理,讓您能夠將字串格式的數字轉換為整數。

在本文中,我們將深入探討如何在 C# 中使用 ParseInt 將數字的字串表示轉換為整數,以及 IronPDF 如何簡化從 PDF 中提取和解析數據的過程。

在 C# 中,什麼是 ParseInt?

解析整數的基礎知識

在 C# 中,轉換字串值(例如「123」)將字串轉換為整數通常使用 int.Parse。()或Convert.ToInt32(). 這些方法幫助開發人員將文字數據轉換為可用於計算和驗證的數值。

  • int.Parse(字串 s):將字串轉換為整數。 如果字串不是有效的整數,則拋出例外。
  • Convert.ToInt32(字串 s):將字串轉換為整數,並以不同方式處理空值輸入。

    以下是使用 int.Parse 轉換字串的範例():

string numberString = "123";
int num = int.Parse(numberString);
Console.WriteLine(num); // Output: 123
string numberString = "123";
int num = int.Parse(numberString);
Console.WriteLine(num); // Output: 123
Dim numberString As String = "123"
Dim num As Integer = Integer.Parse(numberString)
Console.WriteLine(num) ' Output: 123
VB   C#

或者,使用 Convert 類別:

string numericString = "123";
int i = Convert.ToInt32(numericString);
Console.WriteLine(result); // Outputs: 123
string numericString = "123";
int i = Convert.ToInt32(numericString);
Console.WriteLine(result); // Outputs: 123
Dim numericString As String = "123"
Dim i As Integer = Convert.ToInt32(numericString)
Console.WriteLine(result) ' Outputs: 123
VB   C#

Convert 類別允許您安全地轉換字串和其他資料類型。 當字串變數可能代表空值或無效值時,它特別有用,例如 Convert.ToInt32。()返回默認值(在這種情況下為0)而不是拋出異常。

預設值和錯誤處理

開發人員在將字串轉換為整數時經常面臨的一個問題是處理無效或非數字的輸入。 如果數字的字串表示形式不是正確格式,像 int.Parse 這樣的方法()將拋出異常。 然而,Convert.ToInt32()具有內建的回退機制來處理無效字串。

以下是一個示例,說明在解析時如何處理預設值:

string invalidString = "abc";
int result = Convert.ToInt32(invalidString); // Returns 0 (default value) instead of throwing an error.
Console.WriteLine(result); // Outputs: 0
string invalidString = "abc";
int result = Convert.ToInt32(invalidString); // Returns 0 (default value) instead of throwing an error.
Console.WriteLine(result); // Outputs: 0
Dim invalidString As String = "abc"
Dim result As Integer = Convert.ToInt32(invalidString) ' Returns 0 (default value) instead of throwing an error.
Console.WriteLine(result) ' Outputs: 0
VB   C#

如果您想要更精確地控制字串轉換,可以使用int.TryParse()返回一個布林值,指示轉換是否成功:

string invalidInput = "abc";
if (int.TryParse(invalidInput, out int result))
{
    Console.WriteLine(result);
}
else
{
    Console.WriteLine("Parsing failed.");
}
string invalidInput = "abc";
if (int.TryParse(invalidInput, out int result))
{
    Console.WriteLine(result);
}
else
{
    Console.WriteLine("Parsing failed.");
}
Dim invalidInput As String = "abc"
Dim result As Integer
If Integer.TryParse(invalidInput, result) Then
	Console.WriteLine(result)
Else
	Console.WriteLine("Parsing failed.")
End If
VB   C#

在這種情況下,TryParse()使用輸出參數來存儲轉換後的整數,這樣即使轉換失敗,該方法也能返回一個值而不會拋出異常。轉換失敗時,將執行 else 語句,而不是簡單地崩潰程序。 否則,程序將顯示成功解析的輸入字串中的數字結果。 使用 int.TryParse 在轉換失敗可能預期的情況下很有幫助,並且您想避免程式崩潰。

使用 IronPDF 解析 PDF 中的數據

為什麼使用 IronPDF 來解析數據?

Parseint C#(開發人員如何運作):圖1

在處理PDF文件時,您可能會遇到包含字串形式數據的表格或非結構化文本。 要提取和處理這些數據,將字串轉換為整數是至關重要的。 IronPDF 使這個過程變得簡單,提供了靈活性和強大的功能來讀取 PDF 內容,並執行將字串轉換為數值等操作。

以下是IronPDF提供的一些主要功能:

  • HTML 轉換成 PDF:IronPDF 可以轉換HTML 內容 (包括 CSS、圖片和 JavaScript)轉換為完整格式的 PDF。 這對於將動態網頁或報告渲染為PDF特別有用。
  • PDF 編輯: 使用 IronPDF,您可以通過添加文字、圖片和圖形來操作現有的 PDF 文檔,以及编辑現有頁面的內容。
  • 文字和圖片提取:該函式庫允許您Extract text and images從 PDFs 中提取,使解析和分析 PDF 內容變得輕鬆。
  • 水印:也可以添加浮水印到 PDF 文件進行品牌或版權保護。

入門 IronPDF

要開始使用IronPDF,您首先需要安裝它。 如果已經安裝,則可以跳到下一部分。否則,以下步驟將介紹如何安裝IronPDF庫。

透過 NuGet 套件管理器主控台

To安裝 IronPDF使用 NuGet 套件管理器主控台,開啟 Visual Studio 並導航至套件管理器主控台。 然後執行以下命令:

Install-Package IronPdf
Install-Package IronPdf
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'Install-Package IronPdf
VB   C#

透過 NuGet 封裝管理器為方案進行操作

打開 Visual Studio,前往「工具 -> NuGet 套件管理員 -> 為方案管理 NuGet 套件」並搜尋 IronPDF。 從這裡開始,您只需選擇您的專案並點擊「安裝」,IronPDF 就會被添加到您的專案中。

Parseint C#(對開發人員的運作方式):圖2

安裝 IronPDF 後,您只需在程式碼的頂部新增正確的 using 語句即可開始使用 IronPDF:

using IronPdf;
using IronPdf;
Imports IronPdf
VB   C#

解鎖免費試用

IronPDF 提供一個免費試用全面使用其功能。 訪問IronPDF 網站下載試用並開始將先進的 PDF 處理集成到您的 .NET 專案中。

範例:從 PDF 中提取並解析數字

以下 C# 程式碼演示如何使用 IronPDF 從 PDF 中提取文本,然後使用正則表達式在提取的文本中查找和解析所有數值。 該程式碼處理整數和小數,清除貨幣符號等非數字字符。

using IronPdf;
using System.Text.RegularExpressions;
public class Program
{
    public static void Main(string[] args)
    {
        // Load a PDF file
        PdfDocument pdf = PdfDocument.FromFile("example.pdf");
        // Extract all text from the PDF
        string text = pdf.ExtractAllText();
        // Print the extracted text (for reference)
        Console.WriteLine("Extracted Text: ");
        Console.WriteLine(text);
        // Parse and print all numbers found in the extracted text
        Console.WriteLine("\nParsed Numbers:");
        // Use regular expression to find all number patterns, including integers and decimals
        var numberMatches = Regex.Matches(text, @"\d+(\.\d+)?");
        // Iterate through all matched numbers and print them
        foreach (Match match in numberMatches)
        {
            // Print each matched number
            Console.WriteLine($"{match.Value}");
        }
    }
}
using IronPdf;
using System.Text.RegularExpressions;
public class Program
{
    public static void Main(string[] args)
    {
        // Load a PDF file
        PdfDocument pdf = PdfDocument.FromFile("example.pdf");
        // Extract all text from the PDF
        string text = pdf.ExtractAllText();
        // Print the extracted text (for reference)
        Console.WriteLine("Extracted Text: ");
        Console.WriteLine(text);
        // Parse and print all numbers found in the extracted text
        Console.WriteLine("\nParsed Numbers:");
        // Use regular expression to find all number patterns, including integers and decimals
        var numberMatches = Regex.Matches(text, @"\d+(\.\d+)?");
        // Iterate through all matched numbers and print them
        foreach (Match match in numberMatches)
        {
            // Print each matched number
            Console.WriteLine($"{match.Value}");
        }
    }
}
Imports Microsoft.VisualBasic
Imports IronPdf
Imports System.Text.RegularExpressions
Public Class Program
	Public Shared Sub Main(ByVal args() As String)
		' Load a PDF file
		Dim pdf As PdfDocument = PdfDocument.FromFile("example.pdf")
		' Extract all text from the PDF
		Dim text As String = pdf.ExtractAllText()
		' Print the extracted text (for reference)
		Console.WriteLine("Extracted Text: ")
		Console.WriteLine(text)
		' Parse and print all numbers found in the extracted text
		Console.WriteLine(vbLf & "Parsed Numbers:")
		' Use regular expression to find all number patterns, including integers and decimals
		Dim numberMatches = Regex.Matches(text, "\d+(\.\d+)?")
		' Iterate through all matched numbers and print them
		For Each match As Match In numberMatches
			' Print each matched number
			Console.WriteLine($"{match.Value}")
		Next match
	End Sub
End Class
VB   C#

輸入 PDF

Parseint C#(對開發人員的運作方式):圖 3

控制台輸出

Parseint C#(對開發人員的運作方式):圖4

程式碼說明

  1. 從 PDF 中提取文字

    該程式碼首先使用IronPDF加載PDF檔案。 然後從 PDF 中提取所有文字。

  2. 使用正則表達式查找數字

    代碼使用了正則表達式(匹配文本的模式)在提取的文本中搜索並找到任何數字。 正規表達式尋找整數(例如,12345)和十進位數字(例如,50.75).

  3. 解析和列印數字

    一旦找到這些數字,程式會將每個數字打印到控制台。 這包括整數和小數。

  4. 為什麼選擇正則表達式

    正規表示式被使用是因為它們是尋找文本中模式(如數字)的強大工具。 他們可以處理帶有符號的數字(如貨幣符號 $),使該過程更具彈性。

常見挑戰及IronPDF的解決方案

從複雜的 PDF 結構中提取乾淨數據通常會產生可能需要進一步處理的字串值,例如將字串轉換為整數。 以下是一些常見的挑戰,以及IronPDF如何提供幫助:

PDF中的格式錯誤

PDF通常包含格式化為文字的數字(例如,「1,234.56」或「12,345 美元」). 要正確處理這些內容,需要確保數字的字串表示形式是正確的解析格式。 IronPDF 允許您清晰地提取文本,並且您可以使用字符串操作方法。(例如,替換())在轉換之前調整格式。

範例:

string formattedNumber = "1,234.56"; // String value with commas
string cleanNumber = formattedNumber.Replace(",", ""); // Remove commas
int result = Convert.ToInt32(Convert.ToDouble(cleanNumber)); // Convert to integer
Console.WriteLine(result); // Outputs: 1234
string formattedNumber = "1,234.56"; // String value with commas
string cleanNumber = formattedNumber.Replace(",", ""); // Remove commas
int result = Convert.ToInt32(Convert.ToDouble(cleanNumber)); // Convert to integer
Console.WriteLine(result); // Outputs: 1234
Dim formattedNumber As String = "1,234.56" ' String value with commas
Dim cleanNumber As String = formattedNumber.Replace(",", "") ' Remove commas
Dim result As Integer = Convert.ToInt32(Convert.ToDouble(cleanNumber)) ' Convert to integer
Console.WriteLine(result) ' Outputs: 1234
VB   C#

在文本中處理多個數值

在複雜的 PDF 中,數值可能會以不同的格式出現,或分散在不同的位置。 使用 IronPDF,您可以提取所有文本,然後使用正則表達式高效地查找和將字串轉換為整數。

結論

在 C# 中解析整數是開發人員的一項基本技能,特別是在處理用戶輸入或從各種來源提取數據時。 內建的方法如 int.Parse()和 Convert.ToInt32()處理非結構化或半結構化數據(如 PDF 中的文本)可能會帶來額外的挑戰。 這就是 IronPDF 發揮作用的地方,提供了一種強大且簡單的方法,用於從 PDF 中提取文字並在 .NET 應用程式中使用。

通过使用IronPDF您將能輕鬆從複雜的 PDF 檔案中提取文字,包括掃描文件,並將該數據轉換為可用的數值。 借助掃描 PDF 的 OCR 功能和強大的文本提取工具,IronPDF 使您能夠簡化數據處理,即使是在具有挑戰性的格式中。

無論您正在處理發票、財務報告或其他包含數據的文檔,將 C# 的 ParseInt 方法與 IronPDF 結合使用,將幫助您更高效且準確地工作。

不要讓複雜的PDF減緩您的開發過程——開始使用IronPDF這是探索 IronPDF 如何提升您的工作流程的絕佳機會,何不試試看,看看它如何使您的下一個項目更加流暢?

< 上一頁
C# 時間跨度格式(開發人員如何使用)
下一個 >
C# MySQL 連線(開發人員的運作方式)