跳過到頁腳內容
.NET幫助

C# 字串替換(開發者的工作原理)

無論您是程式設計的新手,或只是想更了解如何在 C# 中操作字串,您都來對地方了。 在本教程中,我們將透過親切的真實範例和故事來探討 C# 中的 replace 方法,使其引人入勝,容易跟隨。

基本知識:什麼是字串?

在深入了解"字串 replace "方法之前,我們先來探討一下字串的基本知識。 字串是一連串的字元,可以包含字母、數字和符號。 在 C# 中,字串由 string 資料類型表示。 這些工具對於在程式中處理文字是不可或缺的,並有大量的內建方法來處理它們。 其中一種方法是"取代"法,我們將在本教學中重點介紹。

介紹取代方法

想像您正在撰寫一個需要使用者輸入句子的應用程式。 您的應用程式需要以新的字詞取代特定的字詞。 這時 C# 中的 replace 方法就派上了用場。

replace 方法是一個內建函式,可讓您使用新字串取代指定 Unicode 字元或子字串的所有出現位置。 假設您有以下字串:"我愛吃冰淇淋"。您想要將 "ice "這個字換成 "chocolate",以建立一個新的字串:"I love chocolate cream"。replace 方法使這項任務變得簡單而有效率。

使用取代方法:步驟指南

要使用取代法,請遵循以下簡單步驟:

1.宣告一個包含原始文字的字串變數。 2.在指定字串上呼叫 replace 方法,提供要取代的字元或子串以及新字串。 3.將結果儲存於新的字串變數或更新原始字串。

以下是示範這些步驟的程式碼範例:

// Declare the original text
string originalText = "I love ice cream.";

// Use the Replace method to replace 'ice' with 'chocolate'
string newText = originalText.Replace("ice", "chocolate");

// Output the modified string
Console.WriteLine(newText);
// Declare the original text
string originalText = "I love ice cream.";

// Use the Replace method to replace 'ice' with 'chocolate'
string newText = originalText.Replace("ice", "chocolate");

// Output the modified string
Console.WriteLine(newText);
' Declare the original text
Dim originalText As String = "I love ice cream."

' Use the Replace method to replace 'ice' with 'chocolate'
Dim newText As String = originalText.Replace("ice", "chocolate")

' Output the modified string
Console.WriteLine(newText)
$vbLabelText   $csharpLabel

此程式碼片段將輸出修改後的字串:"我喜歡巧克力奶油"。

取代方法的不同變體

在 C# 中,replace 方法有兩個重載版本,以滿足不同的需求。 讓我們仔細看看它們:

重置指定的 Unicode 字元

第一版的取代方法允許您以新字元取代指定的 Unicode 字元。 此版本的語法為

public string Replace(char oldChar, char newChar);
public string Replace(char oldChar, char newChar);
public String Replace(Char oldChar, Char newChar)
$vbLabelText   $csharpLabel

以下是說明其用途的範例:

// Original string with numbers
string originalText = "H3ll0 W0rld!";

// Replace '3' with 'e' and '0' with 'o'
string newText = originalText.Replace('3', 'e').Replace('0', 'o');

// Output the modified string
Console.WriteLine(newText);
// Original string with numbers
string originalText = "H3ll0 W0rld!";

// Replace '3' with 'e' and '0' with 'o'
string newText = originalText.Replace('3', 'e').Replace('0', 'o');

// Output the modified string
Console.WriteLine(newText);
' Original string with numbers
Dim originalText As String = "H3ll0 W0rld!"

' Replace '3' with 'e' and '0' with 'o'
Dim newText As String = originalText.Replace("3"c, "e"c).Replace("0"c, "o"c)

' Output the modified string
Console.WriteLine(newText)
$vbLabelText   $csharpLabel

輸出將會是"Hello World!"

重置子串

replace 方法的第二個版本允許您使用新字串取代指定的子串。 此版本的語法為

public string Replace(string oldValue, string newValue);
public string Replace(string oldValue, string newValue);
public String Replace(String oldValue, String newValue)
$vbLabelText   $csharpLabel

以下是說明其用途的範例:

// Original string
string originalText = "I have a red car and a red hat.";

// Replace "red" with "blue"
string newText = originalText.Replace("red", "blue");

// Output the modified string
Console.WriteLine(newText);
// Original string
string originalText = "I have a red car and a red hat.";

// Replace "red" with "blue"
string newText = originalText.Replace("red", "blue");

// Output the modified string
Console.WriteLine(newText);
' Original string
Dim originalText As String = "I have a red car and a red hat."

' Replace "red" with "blue"
Dim newText As String = originalText.Replace("red", "blue")

' Output the modified string
Console.WriteLine(newText)
$vbLabelText   $csharpLabel

輸出的內容會是"我有一輛藍色的汽車和一頂藍色的帽子"。

大小寫敏感性和取代方法

值得注意的是,取代方法是區分大小寫的。這表示如果您要取代指定的 Unicode 字元或子字串,大小寫必須完全符合。 例如,考慮以下程式碼片段:

// Original string with mixed casing
string originalText = "Cats are great pets, but some people prefer CATS.";

// Replace uppercase "CATS" with "dogs"
string newText = originalText.Replace("CATS", "dogs");

// Output the modified string
Console.WriteLine(newText);
// Original string with mixed casing
string originalText = "Cats are great pets, but some people prefer CATS.";

// Replace uppercase "CATS" with "dogs"
string newText = originalText.Replace("CATS", "dogs");

// Output the modified string
Console.WriteLine(newText);
' Original string with mixed casing
Dim originalText As String = "Cats are great pets, but some people prefer CATS."

' Replace uppercase "CATS" with "dogs"
Dim newText As String = originalText.Replace("CATS", "dogs")

' Output the modified string
Console.WriteLine(newText)
$vbLabelText   $csharpLabel

輸出的內容將會是"貓是很棒的寵物,但有些人更喜歡狗"。

請注意,只有大寫的 "CATS "被取代,小寫的 "Cats "保持不變。 如果要執行不區分大小寫的替換,您需要將原始字串和搜尋字串轉換為共通的大小寫(大寫或小寫),然後執行替換。 以下是一個範例:

// Original string
string originalText = "Cats are great pets, but some people prefer CATS.";

// Convert the original string to lowercase
string lowerCaseText = originalText.ToLower();

// Replace "cats" with "dogs" in the lowercase string
string newText = lowerCaseText.Replace("cats", "dogs");

// Output the modified string
Console.WriteLine(newText);
// Original string
string originalText = "Cats are great pets, but some people prefer CATS.";

// Convert the original string to lowercase
string lowerCaseText = originalText.ToLower();

// Replace "cats" with "dogs" in the lowercase string
string newText = lowerCaseText.Replace("cats", "dogs");

// Output the modified string
Console.WriteLine(newText);
' Original string
Dim originalText As String = "Cats are great pets, but some people prefer CATS."

' Convert the original string to lowercase
Dim lowerCaseText As String = originalText.ToLower()

' Replace "cats" with "dogs" in the lowercase string
Dim newText As String = lowerCaseText.Replace("cats", "dogs")

' Output the modified string
Console.WriteLine(newText)
$vbLabelText   $csharpLabel

輸出的內容將會是"狗是很好的寵物,但有些人更喜歡狗"。

請記住,這種方法也會改變整個字串的詞彙套用。 如果您想要保留原始的大小寫,您可以使用 Regex.Replace 方法並加上 RegexOptions.IgnoreCase 旗標。

鏈結取代方法的力量

您也可以將多個 replace 方法串連起來,在一行程式碼中執行數個取代。 當您需要以不同的新字串取代多個字元或子串時,此功能尤其有用。 以下是一個範例:

// Original string with numbers
string originalText = "H3ll0 W0rld!";

// Replace '3' with 'e' and '0' with 'o' using chained Replace methods
string newText = originalText.Replace('3', 'e').Replace('0', 'o');

// Output the modified string
Console.WriteLine(newText);
// Original string with numbers
string originalText = "H3ll0 W0rld!";

// Replace '3' with 'e' and '0' with 'o' using chained Replace methods
string newText = originalText.Replace('3', 'e').Replace('0', 'o');

// Output the modified string
Console.WriteLine(newText);
' Original string with numbers
Dim originalText As String = "H3ll0 W0rld!"

' Replace '3' with 'e' and '0' with 'o' using chained Replace methods
Dim newText As String = originalText.Replace("3"c, "e"c).Replace("0"c, "o"c)

' Output the modified string
Console.WriteLine(newText)
$vbLabelText   $csharpLabel

輸出將會是"Hello World!"

正則表示式與 Replace 方法

雖然 replace 方法非常適合簡單的字串替換,但您可能需要更進階的功能來處理複雜的情境。 在這種情況下,您可以使用正則表達式和 Regex.Replace 方法來執行進階的字串操作。

Regex.Replace 方法允許您在原始字串中搜尋模式,並將其取代為新字串。 您可以使用正則表達式來匹配模式,指定大小寫不敏感等選項,甚至使用擷取群組進行動態取代。

以下是使用 Regex.Replace 方法以新字串取代所有出現的模式的範例:

using System.Text.RegularExpressions;

// Original text with numbers
string originalText = "100 cats, 25 dogs, and 50 birds.";

// Regular expression pattern to match one or more digits
string pattern = @"\d+";

// Replace all digit sequences with the word "many"
string newText = Regex.Replace(originalText, pattern, "many");

// Output the modified string
Console.WriteLine(newText);
using System.Text.RegularExpressions;

// Original text with numbers
string originalText = "100 cats, 25 dogs, and 50 birds.";

// Regular expression pattern to match one or more digits
string pattern = @"\d+";

// Replace all digit sequences with the word "many"
string newText = Regex.Replace(originalText, pattern, "many");

// Output the modified string
Console.WriteLine(newText);
Imports System.Text.RegularExpressions

' Original text with numbers
Private originalText As String = "100 cats, 25 dogs, and 50 birds."

' Regular expression pattern to match one or more digits
Private pattern As String = "\d+"

' Replace all digit sequences with the word "many"
Private newText As String = Regex.Replace(originalText, pattern, "many")

' Output the modified string
Console.WriteLine(newText)
$vbLabelText   $csharpLabel

輸出的內容將會是"許多貓、許多狗、許多鳥"。

在這個範例中,我們使用正規表達模式 \d+ 來匹配任何一個或多個數字的序列,並將其取代為單字"many"。

IronPDF:在 C# 中使用字串替換生成 PDF;

您可以利用 IronPDF 強大的 HTML 至 PDF 的轉換能力,並結合 C# 字串取代方法來建立動態 PDF 文件。

using IronPdf;

class Program
{
    static void Main(string[] args)
    {
        var renderer = new ChromePdfRenderer();

        // Convert HTML String to PDF
        var htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>";
        var pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent);
        pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf");

        // Convert HTML File to PDF
        var htmlFilePath = "path_to_your_html_file.html"; // Specify the path to your HTML file
        var pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath);
        pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf");

        // Convert URL to PDF
        var url = "http://ironpdf.com"; // Specify the URL
        var pdfFromUrl = renderer.RenderUrlAsPdf(url);
        pdfFromUrl.SaveAs("URLToPDF.pdf");
    }
}
using IronPdf;

class Program
{
    static void Main(string[] args)
    {
        var renderer = new ChromePdfRenderer();

        // Convert HTML String to PDF
        var htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>";
        var pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent);
        pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf");

        // Convert HTML File to PDF
        var htmlFilePath = "path_to_your_html_file.html"; // Specify the path to your HTML file
        var pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath);
        pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf");

        // Convert URL to PDF
        var url = "http://ironpdf.com"; // Specify the URL
        var pdfFromUrl = renderer.RenderUrlAsPdf(url);
        pdfFromUrl.SaveAs("URLToPDF.pdf");
    }
}
Imports IronPdf

Friend Class Program
	Shared Sub Main(ByVal args() As String)
		Dim renderer = New ChromePdfRenderer()

		' Convert HTML String to PDF
		Dim htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>"
		Dim pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent)
		pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf")

		' Convert HTML File to PDF
		Dim htmlFilePath = "path_to_your_html_file.html" ' Specify the path to your HTML file
		Dim pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath)
		pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf")

		' Convert URL to PDF
		Dim url = "http://ironpdf.com" ' Specify the URL
		Dim pdfFromUrl = renderer.RenderUrlAsPdf(url)
		pdfFromUrl.SaveAs("URLToPDF.pdf")
	End Sub
End Class
$vbLabelText   $csharpLabel

開始使用 IronPdf

要開始使用 IronPDF for PDF Generation,您首先需要安裝 IronPDF NuGet 套件。 您可以在套件管理員控制台執行下列指令來完成:

Install-Package IronPdf

或者,您可以在 Visual Studio 中的 NuGet Package Manager 中搜尋"IronPDF",然後從那裡安裝。

使用字串替換建立 PDF

比方說,您想要建立一個 使用佔位符取代 HTML 的 PDF 報告,針對不同使用者顯示自訂的問候語。 您可以使用 C# string replace 方法將 HTML 模板中的占位符更換為實際的使用者資料,然後再使用 IronPDF 將 HTML 轉換為 PDF 文件。

以下是如何完成此工作的逐步指南:

建立一個有使用者資料佔位符的 HTML 模板。

<!-- HTML template with placeholders -->
<!DOCTYPE html>
<html>
<head>
    <title>Personalized Greeting</title>
</head>
<body>
    <h1>Hello, {USERNAME}!</h1>
    <p>Welcome to our platform. Your email address is {EMAIL}.</p>
</body>
</html>
<!-- HTML template with placeholders -->
<!DOCTYPE html>
<html>
<head>
    <title>Personalized Greeting</title>
</head>
<body>
    <h1>Hello, {USERNAME}!</h1>
    <p>Welcome to our platform. Your email address is {EMAIL}.</p>
</body>
</html>
HTML

使用 C# string replace 方法將佔位符取代為實際的使用者資料。

// Read the HTML template from a file
string htmlTemplate = File.ReadAllText("greeting_template.html");

// Replace placeholders with actual user data
string personalizedHtml = htmlTemplate.Replace("{USERNAME}", "John Doe")
                                      .Replace("{EMAIL}", "john.doe@example.com");
// Read the HTML template from a file
string htmlTemplate = File.ReadAllText("greeting_template.html");

// Replace placeholders with actual user data
string personalizedHtml = htmlTemplate.Replace("{USERNAME}", "John Doe")
                                      .Replace("{EMAIL}", "john.doe@example.com");
' Read the HTML template from a file
Dim htmlTemplate As String = File.ReadAllText("greeting_template.html")

' Replace placeholders with actual user data
Dim personalizedHtml As String = htmlTemplate.Replace("{USERNAME}", "John Doe").Replace("{EMAIL}", "john.doe@example.com")
$vbLabelText   $csharpLabel

使用 IronPDF 將個人化的 HTML 轉換成 PDF 文件。

using IronPdf;

var renderer = new ChromePdfRenderer();

// Convert the personalized HTML to a PDF document
PdfDocument pdfDocument = renderer.RenderHtmlAsPdf(personalizedHtml);

// Save the PDF document to a file
pdfDocument.SaveAs("PersonalizedGreeting.PDF");
using IronPdf;

var renderer = new ChromePdfRenderer();

// Convert the personalized HTML to a PDF document
PdfDocument pdfDocument = renderer.RenderHtmlAsPdf(personalizedHtml);

// Save the PDF document to a file
pdfDocument.SaveAs("PersonalizedGreeting.PDF");
Imports IronPdf

Private renderer = New ChromePdfRenderer()

' Convert the personalized HTML to a PDF document
Private pdfDocument As PdfDocument = renderer.RenderHtmlAsPdf(personalizedHtml)

' Save the PDF document to a file
pdfDocument.SaveAs("PersonalizedGreeting.PDF")
$vbLabelText   $csharpLabel

C# String Replace (How It Works For Developers) 圖 1 - Output

就是這樣! 您已成功地使用 C# replace 方法和 IronPDF 創建了一個個人化的 PDF 文件。

結論

透過結合 IronPdf 的強大功能與 C# replace 方法的靈活性,您可以建立專為特定使用者或情境量身打造的動態 PDF 文件。 此方法不僅限於個人化的問候語 - 您可以將其用於產生發票、報告、證書等。

IronPDF 提供 免費試用 IronPDF,讓您無需任何初始投資即可探索其功能。 如果您發現它非常適合您的 PDF 生成需求,授權費從 $799 起。

常見問題解答

如何使用 C# 替換字串中的子串?

在 C# 中,您可以使用 replace 方法,以新的字串取代字串中指定子串的所有出現。此方法對於應用程式中動態更新文字等工作非常有用。

PDF 函式庫如何協助在 C# 中產生動態 PDF?

IronPDF 等 PDF 程式庫可用來建立動態 PDF 文件,方法是以實際資料取代 HTML 模板中的占位符。這是透過使用 C# replace 方法在轉換為 PDF 之前更新內容來實現的。

您可以在 C# 中一次取代多個字串嗎?

是的,在 C# 中,您可以將多個 replace 方法串連起來,在一行程式碼中執行數個取代,有效地實現全面的文字更新。

是否可以在 C# 中使用正則表達式與 replace 方法?

是的,對於更複雜的字串操作,您可以使用 C# 中的 Regex.Replace 方法來使用正則表達式。這允許您搜尋和取代模式,而不是固定的子串。

如何用 C# 將 HTML 內容轉換成 PDF 文件?

使用 IronPDF 之類的 PDF 函式庫,您可以將 HTML 字串、檔案或 URL 轉換成 PDF 文件。這對於直接從網頁內容產生報告或發票非常有用。

結合字串替換與 PDF 產生的使用案例有哪些?

將字串替換與 PDF 產生結合,非常適合建立自訂文件,例如個人化證書或發票,在 PDF 轉換之前,範本中的占位符會被特定的使用者資料取代。

如何在 C# 專案中安裝並使用 PDF 產生函式庫?

您可以透過 Visual Studio 中的 NuGet 套件管理員安裝 IronPDF 等 PDF 函式庫,方法是搜尋該函式庫的名稱,或使用套件管理員控制台執行安裝指令。

取代法中大小寫敏感性的意義是什麼?

C# replace 方法是大小寫敏感的,這表示來源字串中的字元或子串的大小寫必須完全符合指定的值才能被取代。這會影響您如何準備要取代的文字。

Jacob Mellor, Team Iron 首席技术官
首席技术官

Jacob Mellor 是 Iron Software 的首席技術官,作為 C# PDF 技術的先鋒工程師。作為 Iron Software 核心代碼的原作者,他自開始以來塑造了公司產品架構,與 CEO Cameron Rimington 一起將其轉變為一家擁有超過 50 名員工的公司,為 NASA、特斯拉 和 全世界政府機構服務。

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

他的旗艦產品 IronPDF & Iron Suite .NET 庫在全球 NuGet 被安裝超過 3000 萬次,其基礎代碼繼續為世界各地的開發工具提供動力。擁有 25 年的商業經驗和 41 年的編碼專業知識,Jacob 仍專注於推動企業級 C#、Java 及 Python PDF 技術的創新,同時指導新一代技術領袖。