.NET 幫助

C# 字符串替換(開發人員如何運作)

無論您是程式設計的新手,還是只是想更好地了解如何在 C# 中操作字串,您都來對地方了。 在本教程中,我們將透過相關的現實生活範例和故事講述來探索 C# 中的 replace 方法,使其具有吸引力且易於跟隨。

基礎知識:什麼是字串?

在我們深入探討「字串replace」方法之前,讓我們先來探索字串的基本知識。 字串是一組可以包括字母、數字和符號的字符序列。 在 C# 中,字串由 string 資料型別表示。 它們是處理程式中文字的必備工具,並提供大量內建的方法來操作這些文字。 其中一種方法是「replace」方法,我們將在本教程中專注於此方法。

介紹 Replace 方法

假設您正在編寫一個需要使用者輸入句子的應用程式。 您的應用程式需要將特定的字或字元替換為新的字或字元。 這就是 C# 中的 replace 方法派上用場的地方。

replace方法是一個內建函數,可讓您將所有指定的Unicode字元或子字串替換為新的字串。 假設您有以下字串:"I love ice cream." 您想將單詞 "ice" 替換為 "chocolate" 以創建一個新的字串:"I love chocolate cream." 替換方法能讓這個任務變得簡單且高效。

使用替換方法:分步指南

要使用替換方法,請按照以下簡單步驟:

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

  2. 在指定的字串上調用replace方法,提供要被替換的字元或子字串及新字串。

  3. 將結果儲存在新的字串變數中或更新原始字串。

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

string originalText = "I love ice cream.";
string newText = originalText.Replace("ice", "chocolate");
Console.WriteLine(newText);
string originalText = "I love ice cream.";
string newText = originalText.Replace("ice", "chocolate");
Console.WriteLine(newText);
Dim originalText As String = "I love ice cream."
Dim newText As String = originalText.Replace("ice", "chocolate")
Console.WriteLine(newText)
$vbLabelText   $csharpLabel

這段程式碼片段將輸出修改後的字串:"I love chocolate cream."

替換方法的不同變體

在 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

以下是一個用法示例:

string originalText = "H3ll0 W0rld!";
string newText = originalText.Replace('3', 'e');
newText = newText.Replace('0', 'o');
Console.WriteLine(newText);
string originalText = "H3ll0 W0rld!";
string newText = originalText.Replace('3', 'e');
newText = newText.Replace('0', 'o');
Console.WriteLine(newText);
Dim originalText As String = "H3ll0 W0rld!"
Dim newText As String = originalText.Replace("3"c, "e"c)
newText = newText.Replace("0"c, "o"c)
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

以下是一個用法示例:

string originalText = "I have a red car and a red hat.";
string newText = originalText.Replace("red", "blue");
Console.WriteLine(newText);
string originalText = "I have a red car and a red hat.";
string newText = originalText.Replace("red", "blue");
Console.WriteLine(newText);
Dim originalText As String = "I have a red car and a red hat."
Dim newText As String = originalText.Replace("red", "blue")
Console.WriteLine(newText)
$vbLabelText   $csharpLabel

輸出的結果會是:"我有一輛藍色的車和一頂藍色的帽子。"

區分大小寫與替換方法

需要注意的是,replace 方法是區分大小寫的。這意味著,如果嘗試替換指定的 Unicode 字元或子字串,則大小寫必須完全匹配。 例如,請考慮以下程式碼段:

string originalText = "Cats are great pets, but some people prefer CATS.";
string newText = originalText.Replace("CATS", "dogs");
Console.WriteLine(newText);
string originalText = "Cats are great pets, but some people prefer CATS.";
string newText = originalText.Replace("CATS", "dogs");
Console.WriteLine(newText);
Dim originalText As String = "Cats are great pets, but some people prefer CATS."
Dim newText As String = originalText.Replace("CATS", "dogs")
Console.WriteLine(newText)
$vbLabelText   $csharpLabel

輸出會是:「貓是很棒的寵物,但有些人更喜歡狗。」

請注意,只有大寫的 "CATS" 被替換,而小寫的 "Cats" 保持不變。 如果要進行不區分大小寫的替換,您需要將原始字串和搜尋字串轉換為相同的大小寫(可以是大寫或小寫),然後進行替換。 這是個例子:

string originalText = "Cats are great pets, but some people prefer CATS.";
string lowerCaseText = originalText.ToLower();
string newText = lowerCaseText.Replace("cats", "dogs");
Console.WriteLine(newText);
string originalText = "Cats are great pets, but some people prefer CATS.";
string lowerCaseText = originalText.ToLower();
string newText = lowerCaseText.Replace("cats", "dogs");
Console.WriteLine(newText);
Dim originalText As String = "Cats are great pets, but some people prefer CATS."
Dim lowerCaseText As String = originalText.ToLower()
Dim newText As String = lowerCaseText.Replace("cats", "dogs")
Console.WriteLine(newText)
$vbLabelText   $csharpLabel

輸出將是:「狗是很棒的寵物,但有些人更喜歡狗。」

請注意,這種方法也會改變整個字串的大小寫。 如果您想保留原始大小寫,可以使用 Regex.Replace 方法並搭配 RegexOptions.IgnoreCase 標誌。

鏈式替換方法的威力

您還可以將多個替換方法鏈接在一起,以在一行代碼中執行多次替換。 這在您需要將多个字符或子字符串替換為不同的新字符串時特別有用。 這是個例子:

string originalText = "H3ll0 W0rld!";
string newText = originalText.Replace('3', 'e').Replace('0', 'o');
Console.WriteLine(newText);
string originalText = "H3ll0 W0rld!";
string newText = originalText.Replace('3', 'e').Replace('0', 'o');
Console.WriteLine(newText);
Dim originalText As String = "H3ll0 W0rld!"
Dim newText As String = originalText.Replace("3"c, "e"c).Replace("0"c, "o"c)
Console.WriteLine(newText)
$vbLabelText   $csharpLabel

輸出的結果將是:「Hello World!」

在此範例中,我們使用一行代碼將 '3' 替換為 'e',並將 '0' 替換為 'o'。

正則表達式與替換方法

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

Regex.Replace 方法允許您在原始字串中搜尋一個模式,並以新字串中的值替換它。 您可以使用正則表達式來匹配模式,指定選項如不區分大小寫,甚至使用捕獲組來進行動態替換。

這裡是使用Regex.Replace方法將所有模式出現替換為新的空字符串的範例:

using System.Text.RegularExpressions;

string originalText = "100 cats, 25 dogs, and 50 birds.";
string pattern = @"\d+";
string newText = Regex.Replace(originalText, pattern, "many");
Console.WriteLine(newText);
using System.Text.RegularExpressions;

string originalText = "100 cats, 25 dogs, and 50 birds.";
string pattern = @"\d+";
string newText = Regex.Replace(originalText, pattern, "many");
Console.WriteLine(newText);
Imports System.Text.RegularExpressions

Private originalText As String = "100 cats, 25 dogs, and 50 birds."
Private pattern As String = "\d+"
Private newText As String = Regex.Replace(originalText, pattern, "many")
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();

        // 1. 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");

        // 2. 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");

        // 3. 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();

        // 1. 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");

        // 2. 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");

        // 3. 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()

		' 1. 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")

		' 2. 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")

		' 3. 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 套件管理器中搜索 "IronPDF" 並從那裡安裝它。

使用字串替換創建 PDF

假設您想要創建一個從 HTML 中生成 PDF 報告並替換佔位符的功能,以為不同的使用者顯示個性化的問候語。 您可以使用 C# 的字串替換方法來替換 HTML 模板中的佔位符為實際的用戶數據,然後使用 IronPDF 將 HTML 轉換為 PDF 文件。

以下是如何執行此操作的逐步指南:

創建一個包含用戶數據佔位符的 HTML 範本。

Personalized Greeting

Hello, {USERNAME}!
Welcome to our platform. Your email address is {EMAIL}.

使用C#字串替換方法將當前字串及佔位符替換為實際的用戶資料。

string htmlTemplate = File.ReadAllText("greeting_template.html");
string personalizedHtml = htmlTemplate.Replace("{USERNAME}", "John Doe")
                                        .Replace("{EMAIL}", "john.doe@example.com");
string htmlTemplate = File.ReadAllText("greeting_template.html");
string personalizedHtml = htmlTemplate.Replace("{USERNAME}", "John Doe")
                                        .Replace("{EMAIL}", "john.doe@example.com");
Dim htmlTemplate As String = File.ReadAllText("greeting_template.html")
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 IronPDF.ChromePdfRenderer();
PdfDocument pdfDocument = renderer.RenderHtmlAsPdf(personalizedHtml);
using IronPdf;

var renderer = new IronPDF.ChromePdfRenderer();
PdfDocument pdfDocument = renderer.RenderHtmlAsPdf(personalizedHtml);
Imports IronPdf

Private renderer = New IronPDF.ChromePdfRenderer()
Private pdfDocument As PdfDocument = renderer.RenderHtmlAsPdf(personalizedHtml)
$vbLabelText   $csharpLabel

將 PDF 文件儲存到檔案或流式傳輸給使用者。

pdfDocument.SaveAs("PersonalizedGreeting.PDF");
pdfDocument.SaveAs("PersonalizedGreeting.PDF");
pdfDocument.SaveAs("PersonalizedGreeting.PDF")
$vbLabelText   $csharpLabel

C# 字串替換(如何為開發者運作)圖 1 - 輸出

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

結論

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

IronPDF 提供IronPDF 的免費試用版,讓您在無需初期投資的情況下探索其功能。 如果您覺得它非常適合您的 PDF 生成需求,授權價格從$749開始。

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