.NET 幫助

C# 字串方法(開發人員如何運作)

Chipego
奇佩戈·卡林达
2025年4月3日
分享:

在 C# 中處理 PDF 檔案不僅涉及內容的呈現和格式化,還包括根據需求操作文本。 無論您是在提取、搜索還是編輯 PDF 內的文本,了解如何利用C# string 方法都可以顯著增強您的工作流程。 在本文中,我們將探討常見的 C# 字串操作,它們如何應用於IronPDF,以及如何使用它們來簡化您的 PDF 處理任務。

使用 IronPDF 的字串方法介紹

C# 提供多種字串方法,讓您以多種方式處理文字。 從基本的操作如串接和替換,到像正則表達式這樣的高級技術,這些方法在處理 PDF 內容時都是必不可少的。

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

IronPDF:強大的 C# PDF 函式庫

C# 字符串方法(適用於開發者的工作原理):圖 1

從Pixabay添加上傳

或將圖片拖放到此處

新增圖片替代文字

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

主要功能

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

    IronPDF 提供了一套全面的工具,以輕鬆且高效地處理您所有的 PDF 需求。 立即透過免費試用開始探索其強大功能,看看 IronPDF 如何精簡您的 PDF 工作流程!

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"

C# 字串方法 (它如何適用於開發人員):圖 2

從Pixabay添加上傳

或將圖片拖放到此處

新增圖片替代文字

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

var pdfText = "Header: " + extractedHeader + "\n" + "Body: " + extractedBody;
var pdfText = "Header: " + extractedHeader + "\n" + "Body: " + extractedBody;

這演示了如何使用簡單的字串連接將指定的子字串合併成一個連貫的區塊。 正如我們稍後將看到的,這種串聯字符串可以用來為 PDFs 構建動態內容。

PDF 輸出:

C# 字符串方法(開發人員如何運作):圖3

從Pixabay添加上傳

或將圖片拖放到此處

新增圖片替代文字

PDF 輸出字串

使用IronPDF創建新文檔時,文字字串的指定索引位置對於確定頁面上標題或正文等元素的出現位置非常關鍵。 這樣一來,目前的字串物件可以直接影響佈局的決策。

PDF中的文本格式化

一旦您提取和操作了文本,您可能需要先格式化它,然后再將其添加到新的 PDF 中。 IronPDF 允許您使用 RenderHtmlAsPdf 轉換功能設置字體樣式、大小,甚至定位,C# 字符串方法可幫助您動態生成格式化內容。

例如,您可以通過將字符串與HTML標籤串聯來創建動態標頭和正文內容:

string htmlContent = "<h1>" + headerText + "</h1>" + "<p>" + bodyText + "</p>";
string htmlContent = "<h1>" + headerText + "</h1>" + "<p>" + bodyText + "</p>";

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

PdfDocument pdf = HtmlToPdf.ConvertHtmlString(htmlContent);
pdf.SaveAs("formattedDocument.pdf");
PdfDocument pdf = HtmlToPdf.ConvertHtmlString(htmlContent);
pdf.SaveAs("formattedDocument.pdf");

PDF 輸出:

C# 字串方法(開發人員的運作方式):圖 4

從Pixabay添加上傳

或將圖片拖放到此處

新增圖片替代文字

此方法使您能夠輕鬆生成包含動態內容的PDF,同時確保正確的文本格式。 透過從動態內容生成新的字串,您可以將格式化的 HTML 內容字串陣列傳遞給 IronPDF,確保 PDF 輸出符合您的要求。

搜尋指定的子字串

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

string documentText = "Invoice Number: 12345";
bool containsInvoiceNumber = documentText.Contains("Invoice Number");
string documentText = "Invoice Number: 12345";
bool containsInvoiceNumber = documentText.Contains("Invoice Number");

找到字元的指定位置

要在字串中查找指定的字元,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'

這在使用IronPDF從PDF中的文字中提取動態數據(如數字或日期)時會很方便。

PDF 自動化的進階字串技術

正則表達式

對於更複雜的文本提取,正則表達式(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"
}

正則表達式對於具有可變內容或需要捕捉特定格式的文件特別有用。 使用 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();

IronPDF 可以處理大型 PDF 文件,而在您的工作流程中整合 StringBuilder 可確保在生成或操作 PDF 中的大量文本時有更好的性能。

檢查字串實例是否符合模式

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

在 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

PDF 输出

C# 字串方法(開發者如何使用):圖 5

從Pixabay添加上傳

或將圖片拖放到此處

新增圖片替代文字

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

char[] unicodeArray = "Hello * World".ToCharArray();
char[] unicodeArray = "Hello * World".ToCharArray();

這讓字符的操作更精確,特別是在處理各種語言或格式的 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"

此技術在處理發票或任何形式的 PDF 結構化文字時非常有用。

使用 C# 字符串方法生成 PDF

讓我們把一切結合起來,看看一個更全面的例子,說明如何使用 C# 字串方法來生成 PDF 使用 IronPDF。 這個範例將演示如何提取文字,使用字串方法對其進行操作,然後生成格式化的 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.");
    }
}

解釋

  • 資料設定:我們從樣本客戶數據開始,包括客戶的名稱、地址和購買的項目清單。
  • StringBuilder:我們使用StringBuilder來構建發票的HTML內容。這允許我們高效地追加每個內容部分(頁首、客戶詳細信息、購買商品列表和總成本),而不需要創建多個中間字串實例

    • 字串操作

      • 對於每個項目,我們提取價格(在 $ 符號之後),並計算總成本。這是通過使用 Substring() 來獲取指定子字串,並使用 Convert.ToDouble() 將其轉換為數值來完成的。
  • 總成本然後被格式化為小數點後兩位以達到整潔且專業的顯示效果。
  • HTML 轉換為 PDF:在創建發票內容為 HTML 格式後,我們使用 IronPDF 的 RenderHtmlAsPdf() 方法生成 PDF。 結果被儲存為 Invoice_Johndoe.pdf。

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

PDF輸出

C# 字串方法(開發者如何使用):圖 6

從Pixabay添加上傳

或將圖片拖放到此處

新增圖片替代文字

結論

掌握 C# 字串方法在使用 IronPDF 處理 PDF 時可以簡化您的 PDF 處理任務,不論是提取、編輯或格式化內容。 透過利用字串連接、子字串擷取和正則表達式等技術,您可以完全控制 PDF 中的文字,從而實現更具動態性和效率的工作流程。

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

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

Chipego
奇佩戈·卡林达
軟體工程師
Chipego 擁有天生的傾聽技能,這幫助他理解客戶問題,並提供智能解決方案。他在獲得信息技術理學學士學位後,于 2023 年加入 Iron Software 團隊。IronPDF 和 IronOCR 是 Chipego 專注的兩個產品,但隨著他每天找到新的方法來支持客戶,他對所有產品的了解也在不斷增長。他喜歡在 Iron Software 的協作生活,公司內的團隊成員從各自不同的經歷中共同努力,創造出有效的創新解決方案。當 Chipego 離開辦公桌時,他常常享受讀好書或踢足球的樂趣。
< 上一頁
C# Interlocked(如何為開發人員工作)
下一個 >
HTML 美化工具(開發人員的工作原理)