在生產環境中測試,無水印。
在任何需要的地方都能運行。
獲得 30 天的全功能產品。
在幾分鐘內上手運行。
試用產品期間完全訪問我們的支援工程團隊
在使用 C# 處理資料時,開發人員經常需要將數字的文本表示轉換為整數。 這個被稱為「解析整數」的任務,對於各種應用來說都是至關重要的,從處理使用者輸入到從像PDF這樣的文件中提取數據。 儘管 C# 提供強大的解析整數的方法,但在處理如 PDF 中的非結構化或半結構化數據時,過程可能變得更加複雜。
這就是IronPDF,一個供 .NET 開發人員使用的強大 PDF 庫,發揮作用的地方。 使用 IronPDF,您可以從 PDF 中提取文本,並利用 C# 的解析功能將這些文本轉換為可用的數據。 無論您是在分析發票、報告還是表格,結合 C# 的解析工具與 IronPDF 可以簡化 PDF 資料的處理,讓您能夠將字串格式的數字轉換為整數。
在本文中,我們將深入探討如何在 C# 中使用 ParseInt 將數字的字串表示轉換為整數,以及 IronPDF 如何簡化從 PDF 中提取和解析數據的過程。
在 C# 中,將字串值(例如 "123")轉換為整數通常使用 int.Parse() 或 Convert.ToInt32()。 這些方法幫助開發人員將文字數據轉換為可用於計算和驗證的數值。
Convert.ToInt32(string s):將字串轉換為整數,並以不同方式處理 null 輸入。
以下是一個使用 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
或者,使用 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
Convert 類別允許您安全地轉換字串和其他資料類型。 當字串變數可能表示 null 或無效值時,這特別有用,因為 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
如果您想要更精確地轉換字符串,可以使用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
在這種情況下,TryParse() 使用 out 參數來存儲轉換後的整數,這樣即使轉換失敗,方法也能返回一個值而不拋出異常,若轉換失敗則會執行 else 語句,而不是簡單地使程式崩潰。 否則,程序將顯示成功解析的輸入字串中的數字結果。 使用 int.TryParse 在轉換失敗可能預期的情況下很有幫助,並且您想避免程式崩潰。
在處理PDF文件時,您可能會遇到包含字串形式數據的表格或非結構化文本。 要提取和處理這些數據,將字串轉換為整數是至關重要的。 IronPDF 使這個過程變得簡單,提供了靈活性和強大的功能來讀取 PDF 內容,並執行將字串轉換為數值等操作。
以下是IronPDF提供的一些主要功能:
要開始使用IronPDF,您首先需要安裝它。 如果已經安裝,則可以跳到下一部分。否則,以下步驟將介紹如何安裝IronPDF庫。
若要使用 NuGet 套件管理器主控台安裝 IronPDF,請開啟 Visual Studio 並導航至套件管理器主控台。 然後執行以下命令:
Install-Package IronPdf
Install-Package IronPdf
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'Install-Package IronPdf
打開 Visual Studio,前往「工具 -> NuGet 套件管理員 -> 為方案管理 NuGet 套件」並搜尋 IronPDF。 從這裡開始,您只需選擇您的專案並點擊「安裝」,IronPDF 就會被添加到您的專案中。
安裝 IronPDF 後,您只需在程式碼的頂部新增正確的 using 語句即可開始使用 IronPDF:
using IronPdf;
using IronPdf;
Imports IronPdf
IronPDF 提供免費試用,可完整使用其功能。 訪問IronPDF 網站下載試用版,開始將先進的 PDF 處理集成到您的 .NET 專案中。
以下 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
從 PDF 提取文本:
該程式碼首先使用IronPDF加載PDF檔案。 然後從 PDF 中提取所有文字。
使用正則表達式尋找數字:
此代碼使用正則表達式(用於匹配文本的模式)搜尋提取的文本並查找任何數字。 正則表達式同時尋找整數(例如,12345)和小數(例如,50.75)。
解析和打印數字:
一旦找到這些數字,程式會將每個數字打印到控制台。 這包括整數和小數。
為什麼使用正則表達式:
正規表示式被使用是因為它們是尋找文本中模式(如數字)的強大工具。 它們可以處理帶有符號的數字(如貨幣符號 $),使過程更加靈活。
從複雜的 PDF 結構中提取乾淨數據通常會產生可能需要進一步處理的字串值,例如將字串轉換為整數。 以下是一些常見的挑戰,以及IronPDF如何提供幫助:
PDF 文件通常包含格式為文字的數字(例如,"1,234.56" 或 "12,345 USD")。 要正確處理這些內容,需要確保數字的字串表示形式是正確的解析格式。 IronPDF 允許您乾淨地提取文本,並且您可以使用字串操作方法(例如:Replace())在轉換前調整格式。
範例:
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
在複雜的 PDF 中,數值可能會以不同的格式出現,或分散在不同的位置。 使用 IronPDF,您可以提取所有文本,然後使用正則表達式高效地查找和將字串轉換為整數。
在 C# 中解析整數是開發人員的一項基本技能,特別是在處理用戶輸入或從各種來源提取數據時。 雖然內建的方法如 int.Parse() 和 Convert.ToInt32() 很有用,但處理像是 PDF 中找到的文字這樣的非結構化或半結構化資料時,可能會帶來額外的挑戰。 這就是 IronPDF 發揮作用的地方,提供了一種強大且簡單的方法,用於從 PDF 中提取文字並在 .NET 應用程式中使用。
通過使用IronPDF,您可以輕鬆地從包括掃描文件在內的複雜PDF中提取文本,並將這些數據轉換為可用的數值。 借助掃描 PDF 的 OCR 功能和強大的文本提取工具,IronPDF 使您能夠簡化數據處理,即使是在具有挑戰性的格式中。
無論您正在處理發票、財務報告或其他包含數據的文檔,將 C# 的 ParseInt 方法與 IronPDF 結合使用,將幫助您更高效且準確地工作。
不要讓複雜的PDF文件拖慢您的開發過程—開始使用IronPDF是探索IronPDF如何提升您的工作流程的完美機會,為什麼不試試看它如何簡化您的下一個項目呢?