跳過到頁腳內容
.NET幫助

C#字符串方法(對開發者來說是如何工作的)

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

使用 IronPDF 的字串方法簡介

C# 提供了多種字串方法,讓您能以多樣化的方式處理文字。 從基本操作(如連結和替換)到進階技術(如正規表達式),這些方法在處理 PDF 內容時是不可或缺的。

IronPDF 是用 C# 處理 PDF 的強大函式庫,可與這些字串函式無縫整合,為開發人員提供處理 PDF 內容的彈性工具集。 無論您需要提取文字、搜尋模式或處理內容,瞭解如何使用 IronPDF 的 C# 字串方法將有助於您達成目標。

IronPDF:功能強大的 C# PDF 函式庫

C# String Methods (How it Works for Developers):圖 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# String Methods (How it Works for Developers):圖 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# String Methods (How it Works for Developers):圖 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# String Methods (How it Works for Developers):圖 4

此方法可讓您輕鬆產生動態內容的 PDF,同時確保正確的文字格式。 透過動態內容產生新的字串,您可以將格式化的 HTML 內容字串陣列傳送至 IronPDF,確保 PDF 輸出符合您的需求。

搜尋指定的子串

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

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 可確保在 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
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# String Methods (How it Works for Developers):圖 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# String Methods (How it Works for Developers):圖 6

結論

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

IronPDF提供強大的 PDF 操作功能,可與 C# 字串方法無縫配合。 無論您是處理文字萃取、搜尋模式或自動化內容產生,結合 IronPDF 與 C# 字串運算都能為您省時省力。

想瞭解 IronPDF 如何幫助您實現 PDF 自動化? 立即試用 免費試用版,發掘其全部潛力!

常見問題解答

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

要在 C# 中從 PDF 中提取文本,您可以使用 IronPDF 的文本提取功能。通過利用像 extractText() 這樣的方法,您可以輕鬆地從 PDF 文件中獲取文本數據以便進一步操作或分析。

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

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

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

C# 字串操作如連接、替換和搜索可以顯著改善 PDF 內容的操作。通過將這些操作與 IronPDF 集成,開發人員可以更高效地格式化、搜索和修改 PDF 內的文本,實現動態內容生成和自動化文檔處理。

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

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

正則表達式如何增強 PDF 文本操作?

正則表達式通過允許開發人員進行複雜的模式匹配和數據提取來增強 PDF 文本操作。與 IronPDF 結合使用,正則表達式可以用來從非結構化的 PDF 文本中提取特定數據,如日期或發票號。

為什麼在處理大型 PDF 文本內容時偏好使用 StringBuilder?

StringBuilder 在處理大型 PDF 文本內容時被偏好是因為它提供了高效的內存管理和更快的文本追加或修改性能。這使得它非常適合需要在 PDF 中處理或生成大量文本的場景。

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

IronPDF 提供跨平台 PDF 操作,支持 .NET Framework、.NET Core 和 .NET 5/6,可跨 Windows、Linux 和 macOS 使用。這種靈活性確保開發人員能夠在不同環境中創建、編輯和管理 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核心代碼庫的原始開發者,他自公司成立以來就塑造了公司的產品架構,並與CEO Cameron Rimington將公司轉型為服務NASA、Tesla以及全球政府機構的50多人公司。

Jacob擁有曼徹斯特大學土木工程一級榮譽學士學位(1998年–2001年)。他於1999年在倫敦開立首家軟體公司,並於2005年建立了他的第一個.NET組件,專注於解決Microsoft生態系統中的複雜問題。

他的旗艦作品IronPDF和Iron Suite .NET程式庫全球已獲得超過3000萬次NuGet安裝,他的基礎代碼不斷在全球各地驅動開發者工具。擁有25年以上的商業經驗和41年的編碼專業知識,Jacob仍然專注於推動企業級C#、Java和Python PDF技術的創新,同時指導下一代技術領導者。

鋼鐵支援團隊

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