跳至頁尾內容
開發者更新

C# 字串方法大全(開發者完整指南)

使用C#處理PDF不僅僅涉及到渲染和格式化內容,還包括操作文字以滿足您的需求。 無論您是在提取、搜尋還是編輯PDF中的文字,了解如何利用C# 字串方法都能顯著提升您的工作流程。 在本文中,我們將探討常見的C#字串操作,以及它們如何應用於IronPDF,還有如何使用它們來精簡您的PDF處理任務。

使用IronPDF的字串方法簡介

C#提供多種字串方法讓您可以用多種方式處理文字。 從基本操作如連接和替換到高級技巧如正則表達式,這些方法在PDF內容操作中至關重要。

IronPDF是一個強大的C# PDF處理程式庫,無縫整合了這些字串功能,為開發人員提供了一個靈活的工具集來處理PDF內容。 無論您需要提取文字、搜尋模式還是操作內容,了解如何使用與IronPDF的C#字串方法將幫助您實現您的目標。

IronPDF:強大的C# PDF程式庫

C#字串方法(對開發人員的工作原理):圖1

IronPDF是為.NET設計的一個強大PDF程式庫,旨在簡化PDF的建立、操作和自動化。 無論您需要生成動態文件還是提取和編輯內容,IronPDF提供了一個無縫的解決方案,擁有豐富的功能集合。

關鍵特性

  • HTML轉PDF:輕鬆將HTML內容轉換成完全樣式化的PDF。
  • 文字提取:提取並操作現有PDF中的文字。
  • PDF編輯:在PDF中新增文字、圖片註釋或更新現有內容。
  • 數位簽章:在PDF中新增安全的數位簽章
  • PDF/A合規:確保您的PDF符合嚴格的存檔標準
  • 跨平台支持:在Windows、Linux和macOS上運行於.NET Framework、.NET Core和.NET 5/6。

IronPDF提供了全面的工具套件,輕鬆有效地處理您的所有PDF需求。 從今天開始探索其強大的功能,使用免費試用,看看IronPDF如何精簡您的PDF工作流程!

Basic String Operations in C

串接

串接是處理字串時最簡單的操作之一。 在C#中,將兩個或多個字串連接在一起有多種方法,最常見的方法是使用+運算符和String.Concat()

string text1 = "Hello";
string text2 = "World";
string result = text1 + " " + text2;  // Output: "Hello World"
string text1 = "Hello";
string text2 = "World";
string result = text1 + " " + text2;  // Output: "Hello World"
Dim text1 As String = "Hello"
Dim text2 As String = "World"
Dim result As String = text1 & " " & text2 ' Output: "Hello World"
$vbLabelText   $csharpLabel

C#字串方法(對開發人員的工作原理):圖2

使用IronPDF時,您可能需要串接字串以建立完整的文件或操作提取內容的文字。 例如,您可以在應用格式前將PDF文件的標題和正文合併為字串:

var pdfText = "Header: " + extractedHeader + "\n" + "Body: " + extractedBody;
var pdfText = "Header: " + extractedHeader + "\n" + "Body: " + extractedBody;
Imports Microsoft.VisualBasic

Dim pdfText = "Header: " & extractedHeader & vbLf & "Body: " & extractedBody
$vbLabelText   $csharpLabel

這說明了簡單的字串串接如何能將指定的子字串合併成一個連貫的區塊。 正如我們稍後會看到的,這種串接後的字串可以用來構建PDF的動態內容。

PDF輸出:

C#字串方法(對開發人員的工作原理):圖3

PDF輸出字串

在使用IronPDF建立新文件時,字串文字的指定索引位置對決定頁面上如標題或正文等元素的出現位置至關重要。 這樣,當前的字串物件可以直接影響佈局決策。

PDF中的文字格式化

一旦您提取並操作了文字,可能需要在將其新增到新的PDF之前格式化它。 IronPDF允許您使用RenderHtmlAsPdf轉換功能設置字體樣式、大小,甚至是定位,其中C#字串方法可以幫助您動態生成格式化的內容。

例如,您可以透過串接帶有HTML標籤的字串來建立動態的標題和正文內容:

string htmlContent = "<h1>" + headerText + "</h1>" + "<p>" + bodyText + "</p>";
string htmlContent = "<h1>" + headerText + "</h1>" + "<p>" + bodyText + "</p>";
Dim htmlContent As String = "<h1>" & headerText & "</h1>" & "<p>" & bodyText & "</p>"
$vbLabelText   $csharpLabel

然後可以使用IronPDF將該HTML內容轉換為格式良好的PDF:

PdfDocument pdf = HtmlToPdf.ConvertHtmlString(htmlContent);
pdf.SaveAs("formattedDocument.pdf");
PdfDocument pdf = HtmlToPdf.ConvertHtmlString(htmlContent);
pdf.SaveAs("formattedDocument.pdf");
Dim pdf As PdfDocument = HtmlToPdf.ConvertHtmlString(htmlContent)
pdf.SaveAs("formattedDocument.pdf")
$vbLabelText   $csharpLabel

PDF輸出:

C#字串方法(對開發人員的工作原理):圖4

此方法允許您輕鬆生成帶有動態生成內容的PDF,同時確保正確的文字格式化。 透過從動態內容生成新字串,您可以將格式化的HTML內容字串陣列傳遞到IronPDF中,確保PDF輸出符合您的要求。

搜尋指定的子字串

在許多情況下,您需要檢查字串是否包含指定的子字串。 Contains()方法對此很有用,因為它會根據指定字串是否存在於目標字串中返回false

string documentText = "Invoice Number: 12345";
bool containsInvoiceNumber = documentText.Contains("Invoice Number");
string documentText = "Invoice Number: 12345";
bool containsInvoiceNumber = documentText.Contains("Invoice Number");
Dim documentText As String = "Invoice Number: 12345"
Dim containsInvoiceNumber As Boolean = documentText.Contains("Invoice Number")
$vbLabelText   $csharpLabel

查找指定字元的位置

要在字串中查找指定字元,IndexOf()方法特別實用。 它返回字元或子字串在字串中首次出現的指定位置。

string str = "Invoice Number: 12345";
int position = str.IndexOf('5'); // Returns the position of the first '5'
string str = "Invoice Number: 12345";
int position = str.IndexOf('5'); // Returns the position of the first '5'
Dim str As String = "Invoice Number: 12345"
Dim position As Integer = str.IndexOf("5"c) ' Returns the position of the first '5'
$vbLabelText   $csharpLabel

這在使用IronPDF從PDF文字中提取動態資料如數字或日期時非常有用。

用於PDF自動化的高級字串技巧

正則表達式

對於更複雜的文字提取,正則表達式(Regex)提供了一個強大的工具來進行模式匹配。 使用Regex,您可以從非結構化的PDF文字中提取結構化資料,如日期、發票號碼甚至是電郵地址。

using System.Text.RegularExpressions;

string text = "Date: 02/11/2025";
Match match = Regex.Match(text, @"\d{2}/\d{2}/\d{4}");
if (match.Success)
{
    string date = match.Value;  // Output: "02/11/2025"
}
using System.Text.RegularExpressions;

string text = "Date: 02/11/2025";
Match match = Regex.Match(text, @"\d{2}/\d{2}/\d{4}");
if (match.Success)
{
    string date = match.Value;  // Output: "02/11/2025"
}
Imports System.Text.RegularExpressions

Private text As String = "Date: 02/11/2025"
Private match As Match = Regex.Match(text, "\d{2}/\d{2}/\d{4}")
If match.Success Then
	Dim [date] As String = match.Value ' Output: "02/11/2025"
End If
$vbLabelText   $csharpLabel

對於包含可變內容或需要捕獲特定格式的文件,正則表達式特別有用。 將IronPDF與正則表達式結合使用可提取原始文字,幫助自動化任務如表單處理、資料驗證和報告生成。

大文字使用StringBuilder

當處理大塊文字,如多頁內容或資料驅動報告時,使用StringBuilder比普通字串串接更有效率。 StringBuilder專門用於需要追加或修改大量文字,而不建立多個中間字串實例的情況。

StringBuilder sb = new StringBuilder();
sb.AppendLine("Header: " + headerText);
sb.AppendLine("Content: " + bodyText);
string finalText = sb.ToString();
StringBuilder sb = new StringBuilder();
sb.AppendLine("Header: " + headerText);
sb.AppendLine("Content: " + bodyText);
string finalText = sb.ToString();
Dim sb As New StringBuilder()
sb.AppendLine("Header: " & headerText)
sb.AppendLine("Content: " & bodyText)
Dim finalText As String = sb.ToString()
$vbLabelText   $csharpLabel

IronPDF可以處理大型PDF文件,並且在您的工作流程中整合StringBuilder可確保在生成或操作大文字時性能更佳。

檢查字串實例是否匹配模式

Equals()方法可檢查兩個字串實例是否匹配,這意味著它們具有相同的值。 這在PDF內容中進行驗證或比較特別有用。

string str1 = "Invoice";
string str2 = "Invoice";
bool isMatch = str1.Equals(str2); // Returns true as both have the same value
string str1 = "Invoice";
string str2 = "Invoice";
bool isMatch = str1.Equals(str2); // Returns true as both have the same value
Dim str1 As String = "Invoice"
Dim str2 As String = "Invoice"
Dim isMatch As Boolean = str1.Equals(str2) ' Returns true as both have the same value
$vbLabelText   $csharpLabel

在IronPDF中,這可以應用於比較提取的文字以確保其符合所需的格式或值。

處理Unicode字元

在PDF中處理文字時,您可能需要操作或檢查指定的Unicode字元。 IndexOf()方法也可用來查找字串中某個特定Unicode字元的位置。

string unicodeStr = "Hello * World";
int unicodePosition = unicodeStr.IndexOf('*'); // Finds the position of the unicode character
string unicodeStr = "Hello * World";
int unicodePosition = unicodeStr.IndexOf('*'); // Finds the position of the unicode character
Dim unicodeStr As String = "Hello * World"
Dim unicodePosition As Integer = unicodeStr.IndexOf("*"c) ' Finds the position of the unicode character
$vbLabelText   $csharpLabel

PDF輸出

C#字串方法(對開發人員的工作原理):圖5

此外,將字串轉換為unicode字元陣列在處理不同語言或符號的文字時非常有用:

char[] unicodeArray = "Hello * World".ToCharArray();
char[] unicodeArray = "Hello * World".ToCharArray();
Dim unicodeArray() As Char = "Hello * World".ToCharArray()
$vbLabelText   $csharpLabel

這允許對字元進行更精確的操作,尤其是在處理多種語言或格式下的PDF時。

子字串提取與操作

處理字串時的另一個強大功能是能夠提取指定的子字串。 Substring()方法允許您從指定的索引位置開始選擇字串的部分。 這對於從PDF內容中提取有意義的資料必不可少。

string sentence = "Total: $45.00";
string totalAmount = sentence.Substring(7); // Extracts "$45.00"
string sentence = "Total: $45.00";
string totalAmount = sentence.Substring(7); // Extracts "$45.00"
Dim sentence As String = "Total: $45.00"
Dim totalAmount As String = sentence.Substring(7) ' Extracts "$45.00"
$vbLabelText   $csharpLabel

這一技術在處理發票或PDF中的任何結構化文字表格時特別有用。

利用C#字串方法生成PDF

讓我們把所有內容結合起來,看一個更全面的例子,了解C#字串方法如何用於使用IronPDF生成PDF。 這個例子將展示如何提取文字,使用字串方法操作它,然後生成格式化的PDF。

例子:建立自訂發票PDF

想像一下,我們需要動態生成一份發票PDF,從中獲取像客戶的姓名、地址和購買的商品等資訊。 我們將使用各種字串方法來格式化和操作資料,然後生成最終PDF。

using IronPdf;
using System;
using System.Text;

class Program
{
    static void Main()
    {
        // Sample customer data
        string customerName = "John Doe";
        string customerAddress = "123 Main Street, Springfield, IL 62701";
        string[] purchasedItems = { "Item 1 - $10.00", "Item 2 - $20.00", "Item 3 - $30.00" };

        // Start building the HTML content for the invoice
        StringBuilder invoiceContent = new StringBuilder();

        // Adding the header
        invoiceContent.AppendLine("<h1>Invoice</h1>");
        invoiceContent.AppendLine("<h2>Customer Details</h2>");
        invoiceContent.AppendLine("<p><strong>Name:</strong> " + customerName + "</p>");
        invoiceContent.AppendLine("<p><strong>Address:</strong> " + customerAddress + "</p>");

        // Adding the list of purchased items
        invoiceContent.AppendLine("<h3>Items Purchased</h3>");
        invoiceContent.AppendLine("<ul>");
        foreach (var item in purchasedItems)
        {
            invoiceContent.AppendLine("<li>" + item + "</li>");
        }
        invoiceContent.AppendLine("</ul>");

        // Calculate total cost (basic manipulation with string methods)
        double totalCost = 0;
        foreach (var item in purchasedItems)
        {
            string priceString = item.Substring(item.LastIndexOf('$') + 1);
            double price = Convert.ToDouble(priceString);
            totalCost += price;
        }

        // Adding total cost
        invoiceContent.AppendLine("<p><strong>Total Cost:</strong> $" + totalCost.ToString("F2") + "</p>");

        // Convert the HTML to PDF using IronPDF
        var pdf = HtmlToPdf.ConvertHtmlString(invoiceContent.ToString());

        // Save the generated PDF
        pdf.SaveAs("Invoice_Johndoe.pdf");
        Console.WriteLine("Invoice PDF generated successfully.");
    }
}
using IronPdf;
using System;
using System.Text;

class Program
{
    static void Main()
    {
        // Sample customer data
        string customerName = "John Doe";
        string customerAddress = "123 Main Street, Springfield, IL 62701";
        string[] purchasedItems = { "Item 1 - $10.00", "Item 2 - $20.00", "Item 3 - $30.00" };

        // Start building the HTML content for the invoice
        StringBuilder invoiceContent = new StringBuilder();

        // Adding the header
        invoiceContent.AppendLine("<h1>Invoice</h1>");
        invoiceContent.AppendLine("<h2>Customer Details</h2>");
        invoiceContent.AppendLine("<p><strong>Name:</strong> " + customerName + "</p>");
        invoiceContent.AppendLine("<p><strong>Address:</strong> " + customerAddress + "</p>");

        // Adding the list of purchased items
        invoiceContent.AppendLine("<h3>Items Purchased</h3>");
        invoiceContent.AppendLine("<ul>");
        foreach (var item in purchasedItems)
        {
            invoiceContent.AppendLine("<li>" + item + "</li>");
        }
        invoiceContent.AppendLine("</ul>");

        // Calculate total cost (basic manipulation with string methods)
        double totalCost = 0;
        foreach (var item in purchasedItems)
        {
            string priceString = item.Substring(item.LastIndexOf('$') + 1);
            double price = Convert.ToDouble(priceString);
            totalCost += price;
        }

        // Adding total cost
        invoiceContent.AppendLine("<p><strong>Total Cost:</strong> $" + totalCost.ToString("F2") + "</p>");

        // Convert the HTML to PDF using IronPDF
        var pdf = HtmlToPdf.ConvertHtmlString(invoiceContent.ToString());

        // Save the generated PDF
        pdf.SaveAs("Invoice_Johndoe.pdf");
        Console.WriteLine("Invoice PDF generated successfully.");
    }
}
Imports IronPdf
Imports System
Imports System.Text

Friend Class Program
	Shared Sub Main()
		' Sample customer data
		Dim customerName As String = "John Doe"
		Dim customerAddress As String = "123 Main Street, Springfield, IL 62701"
		Dim purchasedItems() As String = { "Item 1 - $10.00", "Item 2 - $20.00", "Item 3 - $30.00" }

		' Start building the HTML content for the invoice
		Dim invoiceContent As New StringBuilder()

		' Adding the header
		invoiceContent.AppendLine("<h1>Invoice</h1>")
		invoiceContent.AppendLine("<h2>Customer Details</h2>")
		invoiceContent.AppendLine("<p><strong>Name:</strong> " & customerName & "</p>")
		invoiceContent.AppendLine("<p><strong>Address:</strong> " & customerAddress & "</p>")

		' Adding the list of purchased items
		invoiceContent.AppendLine("<h3>Items Purchased</h3>")
		invoiceContent.AppendLine("<ul>")
		For Each item In purchasedItems
			invoiceContent.AppendLine("<li>" & item & "</li>")
		Next item
		invoiceContent.AppendLine("</ul>")

		' Calculate total cost (basic manipulation with string methods)
		Dim totalCost As Double = 0
		For Each item In purchasedItems
			Dim priceString As String = item.Substring(item.LastIndexOf("$"c) + 1)
			Dim price As Double = Convert.ToDouble(priceString)
			totalCost += price
		Next item

		' Adding total cost
		invoiceContent.AppendLine("<p><strong>Total Cost:</strong> $" & totalCost.ToString("F2") & "</p>")

		' Convert the HTML to PDF using IronPDF
		Dim pdf = HtmlToPdf.ConvertHtmlString(invoiceContent.ToString())

		' Save the generated PDF
		pdf.SaveAs("Invoice_Johndoe.pdf")
		Console.WriteLine("Invoice PDF generated successfully.")
	End Sub
End Class
$vbLabelText   $csharpLabel

解釋

  • 資料設置:我們從樣本客戶資料開始,包括客戶姓名、地址和購買的商品清單。
  • StringBuilder:我們使用StringBuilder來構建發票的HTML內容。這讓我們可以有效地追加每個部分的內容(如標題、客戶詳情、購買商品清單和總成本),而不需建立多個中間的字串實例

    • 字串操作:

    • 對於每個項目,我們提取價格(在$符號之後)並計算總成本。這是使用Substring()方法獲取指定的子字串,然後使用Convert.ToDouble()將其轉換為數值。

    • 然後總成本被格式化為小數點後兩位,以便清晰且專業地顯示。
  • HTML到PDF的轉換:在建立發票內容的HTML格式後,我們使用IronPDF的RenderHtmlAsPdf()方法來生成PDF。 結果保存為Invoice_Johndoe.pdf。

透過使用IronPDF強大的HTML到PDF轉換功能,並結合C#字串操作技術,您可以自動化動態文件的建立,無論是發票、報告還是合同。

PDF輸出

C#字串方法(對開發人員的工作原理):圖6

結論

掌握在使用IronPDF時的C#字串方法可以精簡您的PDF處理任務,無論您是在提取、編輯還是格式化內容。 透過利用字串串接、子字串提取和正則表達式等技術,您對PDF中的文字擁有完全的控制權,實現更動態和高效的工作流程。

IronPDF提供強大的PDF操作功能,與C#字串方法密切配合。 無論您是在處理文字提取、搜尋模式還是自動化內容生成,將IronPDF與C#字串操作結合將節省您的時間和精力。

想看看IronPDF如何幫助您的PDF自動化嗎? 立即嘗試免費試用,探索其全部潛力!

常見問題

如何在C#中從PDF提取文字?

要在C#中從PDF提取文字,您可以使用IronPDF的文字提取功能。通過使用像extractText()這樣的方法,您可以輕鬆檢索PDF文件中的文字資料以進行進一步處理或分析。

在PDF自動化中使用C#字串方法的最佳實踐是什麼?

對於PDF自動化,最佳實踐包括使用像Substring()這樣的C#字串方法進行文字提取、使用正則表達式進行模式匹配,並在處理大型文件時使用StringBuilder進行高效的文字處理。這些技術結合IronPDF可以增強自動化任務,如表單處理和資料驗證。

C# 字串操作如何改善 PDF 內容操作?

C# 字串操作如串聯、替換和查尋可以顯著改善PDF內容操作。通過將這些操作與IronPDF整合,開發者可以更高效地格式化、查詢和修改PDF中的文字,從而實現動態內容生成和自動化文件處理。

IronPDF 可以用於將 HTML 內容轉換為 PDF 嗎?

是的,IronPDF 提供將 HTML 內容轉換為PDF的功能,通過RenderHtmlAsPdfRenderHtmlFileAsPdf等方法。這使開發者可以輕鬆地將網頁內容或HTML字串轉換為專業的PDF文件。

正則表達式如何增強 PDF 文字處理?

正則表達式增強了PDF文字操作,允許開發者進行複雜的模式匹配和資料提取。結合IronPDF,正則表達式可以用來從非結構化的PDF文字中提取特定資料,如日期或發票號碼。

為什麼 StringBuilder 在處理大型 PDF 文字內容時受到青睞?

StringBuilder 在處理大型PDF文字內容時受到青睞,因為它提供高效的記憶體管理和更快的性能,在附加或修改文字時。這使其在需要在PDF中處理或生成大量文字的情況下成為理想選擇。

using IronPDF 進行跨平台 PDF 操作的優勢是什麼?

IronPDF提供跨平台的PDF操作,支持.NET Framework、.NET Core和.NET 5/6,覆蓋Windows、Linux和macOS。這種靈活性確保開發者可以在多樣的環境中使用IronPDF建立、編輯和管理PDF,而無相容性問題。

我如何使用 C# 字串方法自動化 PDF 生成功能?

您可以透過使用C#字串方法,如串聯和格式化,構建文件內容來自動化PDF生成。一旦內容被準備成HTML字串,IronPDF可以將其轉換為PDF,從而簡化文件建立過程。

C# 字串方法在動態 PDF 文件建立中扮演什麼角色?

C# 字串方法在動態PDF文件建立中發揮關鍵作用,通過支持文字格式化、資料處理和內容組織。使用IronPDF時,這些方法允許開發者快速高效地生成定制和動態PDF文件。

C# 字串方法如何促進 PDF 中的文件編輯?

C# 字串方法透過提供文字查詢、替換和修改工具來促進PDF中的文件編輯。IronPDF利用這些字串功能,使開發者能夠無縫地編輯和更新PDF中的文字內容,提升文件管理工作流程。

Jacob Mellor,首席技術官 @ Team Iron
首席技術官

Jacob Mellor是Iron Software的首席技術官,一位在C# PDF技術上開創先河的遠見工程師。作為Iron Software核心程式碼庫的原開發者,他從創立以來就一直在塑造公司的產品架構,與首席執行官Cameron Rimington一起將公司轉變為服務於NASA、特斯拉和全球政府公司的50多名人員的公司。

Jacob擁有曼徹斯特大學的土木工程一等榮譽學士學位(BEng),於1998-2001年之間獲得。在1999年於倫敦創辦他的第一家軟體公司並於2005年建立了他的第一批.NET元組件後,他專注於解決Microsoft生態系統中的複雜問題。

他的旗艦IronPDF和Iron Suite .NET程式庫在全球獲得了超過3000萬次NuGet安裝依據,他的基礎程式碼基繼續支援著世界各地開發者使用的工具。擁有25年的商業經驗和41年的程式設計專業知識,他仍專注於推動企業級C#、Java和Python PDF技術的創新,同時指導下一代技術領導者。

Iron 支援團隊

我們線上24小時,每週5天。
聊天
電子郵件
給我打電話