跳過到頁腳內容
.NET幫助

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

無論你是編程新手,還是希望更好地了解如何在 C# 中操作字串,你來對地方了。 在本教程中,我們將通過相關的現實案例和敘述來探討 C# 中的 replace 方法,使其既有趣又易於學習。

基礎知識:什麼是字串?

在我們深入瞭解「字串 replace」方法之前,讓我們先來了解字串的基本概念。 字串是一系列可以包括字母、數字和符號的字符。 在 C# 中,字串由 string 資料類型表示。 它們對於程序中的文本處理至關重要,並附帶有大量內建的方法來操作它們。 其中一個這樣的方法就是"replace"方法,我們會在本教程中重點講解。

介紹 Replace 方法

想像一下,你正在編寫一個要求用戶輸入句子的應用程式。 你的應用程式需要將特定的單詞或字符替換為新的詞。 這就是 C# 中的 replace 方法派上用場的時候。

replace 方法是一個內建函數,它允許你將指定的 Unicode 字符或子串的所有出現替換為一個新字串。 假設你有以下字串:「I love ice cream.」,你要將「ice」替換為「chocolate」,以創建一個新字串「I love chocolate cream.」,replace 方法讓這個任務既簡單又高效。

使用 Replace 方法:逐步指南

要使用 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

此代碼片段將輸出修改後的字串:「I love chocolate cream.」。

Replace 方法的不同變體

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

替換特定的 Unicode 字符

replace 方法的第一個版本允許你將指定的 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

輸出將是:「I have a blue car and a blue hat.」

區分大小寫和 Replace 方法

需要注意的是,replace 方法區分大小寫。這意味著如果你嘗試替換特定的 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 are great pets, but some people prefer dogs.」

注意,只有大寫的「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

輸出將是:「dogs are great pets, but some people prefer dogs.」

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

鏈接多個 Replace 方法的力量

你還可以鏈接多個 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

輸出將是:「many cats, many dogs, and many birds.」

在此示例中,我們使用正則表達式模式 \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 進行 PDF 生成,你首先需要安裝 IronPDF NuGet 包。 你可以通过在包管理器控制台中执行以下命令完成此操作:

Install-Package IronPdf

或者,你可以在 Visual Studio 中的 NuGet 包管理器中搜索「IronPDF」,然後從那裡安裝它。

創建帶有字串替換的 PDF

假設你想創建一個顯示不同用戶自定義問候語的HTML 替換占位符生成的 PDF 報告。 你可以使用 C# 的字串替換方法將佔位符替換為實際的用戶數據,然後使用 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# 的字串替換方法將佔位符替換為實際用戶數據。

// 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# 字串替換 (如何為開發者運作) 圖1 - 輸出

就是這樣! 你已經成功使用 C# 的 replace 方法和 IronPDF 創建了一個個性化的 PDF 文檔。

結論

通過結合 IronPDF 的強大功能與 C# replace 方法的靈活性,你可以創建針對特定用戶或場景的動態 PDF 文檔。 這種方法不僅限於個性化問候語——你可以用它來生成發票、報告、證書等等。

IronPDF 提供 IronPDF 的免費試用版,讓你在沒有初始投資的情況下探索其功能。 如果你認為它完全符合你的 PDF 生成需求,許可證從 $799 起。

常見問題解答

如何使用 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 方法是區分大小寫的,意味著源字符串中的字符或子字符串的大小寫必須與指定值完全匹配才能被替換。這會影響您準備文本進行替換的方式。

Curtis Chau
技術作家

Curtis Chau 擁有卡爾頓大學計算機科學學士學位,專注於前端開發,擅長於 Node.js、TypeScript、JavaScript 和 React。Curtis 熱衷於創建直觀且美觀的用戶界面,喜歡使用現代框架並打造結構良好、視覺吸引人的手冊。

除了開發之外,Curtis 對物聯網 (IoT) 有著濃厚的興趣,探索將硬體和軟體結合的創新方式。在閒暇時間,他喜愛遊戲並構建 Discord 機器人,結合科技與創意的樂趣。