跳至頁尾內容
.NET幫助

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

無論您是程式設計的新手,或只是想更了解如何在 C# 中操作字串,您都來對地方了。 在本教程中,我們將使用與現實生活相關的範例和故事來探索 C# 中的 replace 方法,使其引人入勝且易於理解。

基本知識:什麼是字串?

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

介紹取代方法

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

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

使用取代方法:步驟指南

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

1.宣告一個包含原始文字的字串變數。

  1. 對指定的字串呼叫 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: Generating PDFs with String Replacement in C#

您可以利用 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 模板。


<!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>

<!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# 方法的靈活性相結合,您可以建立針對特定使用者或場景量身定制的動態 PDF 文件。 此方法不僅限於個人化的問候語 - 您可以將其用於產生發票、報告、證書等。

IronPDF 提供 免費試用 IronPDF,讓您無需任何初始投資即可探索其功能。 如果您發現它完全符合您的 PDF 生成需求,許可價格從 $999 起。

常見問題

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

在 C# 中,您可以使用 replace 方法將字符串中所有指定子字符串的出現替換為新字符串。此方法對於動態更新應用程式中的文字等任務非常有用。

PDF 庫如何協助在 C# 中生成動態 PDF?

PDF 庫,如 IronPDF,可以通過在 HTML 模板中用實際資料替換佔位符來創建動態 PDF 文件。這是通過使用 C# 的 replace 方法在轉換為 PDF 之前更新內容來實現的。

可以在 C# 中一次替換多個字符串嗎?

是的,在 C# 中,您可以鏈接多個 replace 方法,以在一行代碼中執行多次替換,從而高效地進行全面的文字更新。

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

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

如何在 C# 中將 HTML 內容轉換為 PDF 文檔?

使用像 IronPDF 這樣的 PDF 庫,您可以將 HTML 字符串、文件或 URL 轉換為 PDF 文件。這對於直接從 Web 內容生成報告或發票非常有用。

將字符串替換與 PDF 生成結合使用的某些用例是什麼?

將字符串替換與 PDF 生成結合使用非常適合創建自定義文檔,例如個性化證書或發票,其中模板中的佔位符在 PDF 轉換之前用特定用戶資料替換。

如何在 C# 項目中安裝和使用 PDF 生成庫?

您可以通過在 Visual Studio 的 NuGet 包管理器中搜索庫的名稱來安裝像 IronPDF 這樣的 PDF 庫,也可以使用包管理器控制台運行安裝命令。

replace 方法中的區分大小寫有何重要性?

C# 的 replace 方法是區分大小寫的,意味著源字符串中的字符或子字符串的大小寫必須與指定值完全匹配才能被替換。這會影響您準備文字進行替換的方式。

雅各·梅勒(Jacob Mellor),Team Iron 首席技術長
技術長

雅各·梅勒(Jacob Mellor)是 Iron Software 的首席技術官,也是一位開創 C# PDF 技術的遠見卓識工程師。作為 Iron Software 核心程式碼庫的原始開發者,他自公司成立以來便塑造了產品架構,並與執行長卡梅隆·里明頓(Cameron Rimington)共同將公司發展為擁有 50 多名員工的企業,服務對象包括 NASA、特斯拉(Tesla)及全球政府機構。

雅各布於曼徹斯特大學(1998–2001)取得土木工程一等榮譽工程學士學位(BEng)。他在 1999 年於倫敦創立首家軟體公司,並於 2005 年開發出首批 .NET 元件,此後專注於解決微軟生態系統中的複雜問題。

其旗艦產品 IronPDF 與 Iron Suite .NET 函式庫在全球已累積超過 3,000 萬次 NuGet 安裝,其基礎程式碼持續驅動著全球廣泛使用的開發者工具。憑藉 25 年商業經驗與 41 年程式設計專業,雅各持續致力於推動企業級 C#、Java 及 Python PDF 技術的創新,同時指導新一代技術領導者。

鋼鐵支援團隊

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