跳過到頁腳內容
.NET幫助

C# Replace Character In String(對於開發者的運行原理)

字串處理中常見的操作是變更初始字串中的字元,此時函式會以新字元取代初始字串中指定的 Unicode 字元。 本指南著重於如何使用 C# 中的 Replace 方法,以取代字串目前實例中的字母,這對任何層級的開發人員而言都是有用的技巧。 我們還將瞭解用於 .NET PDF 操作的 IronPDF library 的 PDF 操作。

瞭解取代方法

C# 中的 Replace 方法用於創建一個新的指定字串,方法是將原始字串中所有出現的指定 Unicode 字元或子字串替換成另一個字元或子字串,有效地產生一個不同於目前實例的指定字串。 此方法是 .NET Framework 的 System 命名空間中 String 類的一部分,因此可隨時存取以進行字串操作。

取代法的主要概念

-方法簽章: Replace 方法有兩個主要重載。 一個重載替換字元(char),另一個重載替換子字串(string)。 此方法接受 charstring 作為要替換的舊字元或子字串。 -傳回值:此方法傳回一個新字串,確保原始字串保持不變。 此返回值表示建立一個新的實例,以反映所需的修改。 -參數:它接受兩個參數。 第一個參數指定要取代的字元或子字串,第二個參數指定取代的字元或子字串。

實用範例:取代字元

讓我們來看看使用 Replace 方法取代字串中一個字元的簡單範例。

using System;

class Program
{
    static void Main()
    {
        // The initial string to modify
        string initialString = "Hello World";

        // The character to be replaced
        char oldChar = 'o';

        // The character to replace with
        char newChar = '0';

        // Using Replace method to create a modified string
        string newString = initialString.Replace(oldChar, newChar);

        // Outputting the original and modified strings
        Console.WriteLine("Original String: " + initialString);
        Console.WriteLine("Modified String: " + newString);
    }
}
using System;

class Program
{
    static void Main()
    {
        // The initial string to modify
        string initialString = "Hello World";

        // The character to be replaced
        char oldChar = 'o';

        // The character to replace with
        char newChar = '0';

        // Using Replace method to create a modified string
        string newString = initialString.Replace(oldChar, newChar);

        // Outputting the original and modified strings
        Console.WriteLine("Original String: " + initialString);
        Console.WriteLine("Modified String: " + newString);
    }
}
Imports System

Friend Class Program
	Shared Sub Main()
		' The initial string to modify
		Dim initialString As String = "Hello World"

		' The character to be replaced
		Dim oldChar As Char = "o"c

		' The character to replace with
		Dim newChar As Char = "0"c

		' Using Replace method to create a modified string
		Dim newString As String = initialString.Replace(oldChar, newChar)

		' Outputting the original and modified strings
		Console.WriteLine("Original String: " & initialString)
		Console.WriteLine("Modified String: " & newString)
	End Sub
End Class
$vbLabelText   $csharpLabel

它會在控制台列印以下輸出:

Original String: Hello World
Modified String: Hell0 W0rld

在上面的範例中,初始字串"Hello World"中所有出現的字元 'o" 都會被字元 "0' 取代,展示了該方法如何將每個指定的 Unicode 字元都取代為新字元。 修改後的字串會列印到控制台,並與原始字串並列,以突顯變更。

實用範例:取代子串。

Replacing a substring(取代子串)採用類似的方法,但處理的是字元序列而非個別字元。

using System;

class Program
{
    static void Main()
    {
        // The initial string to modify
        string initialString = "Hello World";

        // The substring to be replaced
        string oldSubstring = "World";

        // The substring to replace with
        string newSubstring = "C#";

        // Using Replace method to create a modified string
        string newString = initialString.Replace(oldSubstring, newSubstring);

        // Outputting the original and modified strings
        Console.WriteLine("Original String: " + initialString);
        Console.WriteLine("Modified String: " + newString);
    }
}
using System;

class Program
{
    static void Main()
    {
        // The initial string to modify
        string initialString = "Hello World";

        // The substring to be replaced
        string oldSubstring = "World";

        // The substring to replace with
        string newSubstring = "C#";

        // Using Replace method to create a modified string
        string newString = initialString.Replace(oldSubstring, newSubstring);

        // Outputting the original and modified strings
        Console.WriteLine("Original String: " + initialString);
        Console.WriteLine("Modified String: " + newString);
    }
}
Imports System

Friend Class Program
	Shared Sub Main()
		' The initial string to modify
		Dim initialString As String = "Hello World"

		' The substring to be replaced
		Dim oldSubstring As String = "World"

		' The substring to replace with
		Dim newSubstring As String = "C#"

		' Using Replace method to create a modified string
		Dim newString As String = initialString.Replace(oldSubstring, newSubstring)

		' Outputting the original and modified strings
		Console.WriteLine("Original String: " & initialString)
		Console.WriteLine("Modified String: " & newString)
	End Sub
End Class
$vbLabelText   $csharpLabel

輸出:

Original String: Hello World
Modified String: Hello C#

此程式碼片段示範在原始字串中以"C#"取代子串"World"。 請注意 Replace 方法是如何以指定的變更來建立新字串,並保留原始字串不變。

取代方法的進階用法

處理多重替換

Replace 方法可以串連,以便在單一語句中執行多個取代。 當您需要取代同一字串中的數個字元或子串時,這將非常有用。

處理特殊情況

-替換為空字串:要刪除所有出現的字元或子字串,只需將其替換為空字串("")。 -區分大小寫: Replace方法區分大小寫。如果需要不區分大小寫的替換,請使用ToLowerToUpper等方法來處理字串。

有效取代字串的提示

  • 請務必記住,Replace 方法不會改變原始字串,而是以指定的修改建立新字串。
  • 如果您要在單一字串上執行大量的取代,請考慮使用 StringBuilder 類別,因為它在某些情況下可以提供更好的效能。

IronPDF:C# PDF 函式庫

IronPDF 是專為在 .NET 環境中處理 PDF 文件而設計的綜合資料庫。 它的主要優勢在於能夠簡化 使用 IronPDF 從 HTML 創建 PDF 的過程。 透過利用 HTML、CSS、圖片和 JavaScript,它能有效率地渲染 PDF,避免使用較耗費人力的傳統 PDF 產生方法。

IronPDF 擅長於 HTML 至 PDF 的轉換,可確保精確保留原始版面與樣式。 它非常適合從網頁內容(如報告、發票和文件)建立 PDF。 IronPDF 支援 HTML 檔案、URL 和原始 HTML 字串,可輕鬆製作高品質的 PDF 文件。

using IronPdf;

class Program
{
    static void Main(string[] args)
    {
        // Initialize a PDF renderer instance
        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)
    {
        // Initialize a PDF renderer instance
        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)
		' Initialize a PDF renderer instance
		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 不僅功能強大,而且使用方便,不需要外部依賴,並提供廣泛的說明文件,幫助使用者快速上手。 其目的在於降低與 PDF 操作相關的複雜性,讓不同技術層級的開發人員都能使用。

程式碼範例

讓我們來探討一個涉及 IronPDF 和取代文字概念的更實際例子。 想像您正在為客戶製作 PDF 發票。 您的應用程式會動態產生發票,其中某些詳細資訊,例如客戶姓名、日期和總金額,會插入預先定義的 HTML 模版中。 此過程將使用您應用程式中的實際資料取代 HTML 中的占位符。 取代這些占位符之後,您使用 IronPDF 將 HTML 轉換成 PDF 文件。

using IronPdf;
using System;

class Program
{
    static void Main()
    {
        // Set your IronPDF license key
        License.LicenseKey = "License-Key";

        // Initialize the HTML to PDF renderer
        var renderer = new ChromePdfRenderer();

        // Example HTML invoice template with placeholders
        string htmlTemplate = @"
<html>
    <head>
        <title>Invoice</title>
    </head>
    <body>
        <h1>Invoice for {CustomerName}</h1>
        <p>Date: {Date}</p>
        <p>Total Amount: {TotalAmount}</p>
    </body>
</html>";

        // Replace placeholders with actual data
        string customerName = "Iron Software";
        string date = DateTime.Today.ToShortDateString();
        string totalAmount = "$100.00";
        string htmlContent = htmlTemplate.Replace("{CustomerName}", customerName)
                                          .Replace("{Date}", date)
                                          .Replace("{TotalAmount}", totalAmount);

        // Generate a PDF from the HTML content
        var pdfDocument = renderer.RenderHtmlAsPdf(htmlContent);

        // Save the PDF document
        pdfDocument.SaveAs("Invoice.pdf");
        Console.WriteLine("Invoice generated successfully.");
    }
}
using IronPdf;
using System;

class Program
{
    static void Main()
    {
        // Set your IronPDF license key
        License.LicenseKey = "License-Key";

        // Initialize the HTML to PDF renderer
        var renderer = new ChromePdfRenderer();

        // Example HTML invoice template with placeholders
        string htmlTemplate = @"
<html>
    <head>
        <title>Invoice</title>
    </head>
    <body>
        <h1>Invoice for {CustomerName}</h1>
        <p>Date: {Date}</p>
        <p>Total Amount: {TotalAmount}</p>
    </body>
</html>";

        // Replace placeholders with actual data
        string customerName = "Iron Software";
        string date = DateTime.Today.ToShortDateString();
        string totalAmount = "$100.00";
        string htmlContent = htmlTemplate.Replace("{CustomerName}", customerName)
                                          .Replace("{Date}", date)
                                          .Replace("{TotalAmount}", totalAmount);

        // Generate a PDF from the HTML content
        var pdfDocument = renderer.RenderHtmlAsPdf(htmlContent);

        // Save the PDF document
        pdfDocument.SaveAs("Invoice.pdf");
        Console.WriteLine("Invoice generated successfully.");
    }
}
Imports IronPdf
Imports System

Friend Class Program
	Shared Sub Main()
		' Set your IronPDF license key
		License.LicenseKey = "License-Key"

		' Initialize the HTML to PDF renderer
		Dim renderer = New ChromePdfRenderer()

		' Example HTML invoice template with placeholders
		Dim htmlTemplate As String = "
<html>
    <head>
        <title>Invoice</title>
    </head>
    <body>
        <h1>Invoice for {CustomerName}</h1>
        <p>Date: {Date}</p>
        <p>Total Amount: {TotalAmount}</p>
    </body>
</html>"

		' Replace placeholders with actual data
		Dim customerName As String = "Iron Software"
		Dim [date] As String = DateTime.Today.ToShortDateString()
		Dim totalAmount As String = "$100.00"
		Dim htmlContent As String = htmlTemplate.Replace("{CustomerName}", customerName).Replace("{Date}", [date]).Replace("{TotalAmount}", totalAmount)

		' Generate a PDF from the HTML content
		Dim pdfDocument = renderer.RenderHtmlAsPdf(htmlContent)

		' Save the PDF document
		pdfDocument.SaveAs("Invoice.pdf")
		Console.WriteLine("Invoice generated successfully.")
	End Sub
End Class
$vbLabelText   $csharpLabel

在此程式碼中

  • HTML 範本:我們從一個表示發票結構的 HTML 範本開始。此範本包含客戶姓名 ({CustomerName})、日期 ({Date}) 和總金額 ({TotalAmount}) 的佔位符。

-替換佔位符:我們將 HTML 模板中的佔位符替換為實際資料。 這與填寫具體細節的表格類似。 在實際應用程式中,這些細節會來自使用者輸入或資料庫。

-產生 PDF:將佔位符替換為實際資料後,我們使用 IronPDF 的HTMLToPdf渲染器將修改後的 HTML 內容轉換為 PDF 文件。

-儲存 PDF:最後,產生的 PDF 檔案儲存為名為"Invoice.pdf"的檔案。 此檔案可隨後傳送給客戶或儲存以作記錄之用。

C# Replace Character In String (How It Works For Developers):圖 1 - PDF 輸出

本範例重點介紹 IronPDF 在商業應用程式中的實際使用案例,特別是如何將動態資料整合至 PDF 文件產生流程中。

結論

C# 中的 Replace 方法是透過取代字元或子串來修改字串的強大工具。 其處理單一及多重取代的能力,再加上簡單直接的語法,使其成為開發人員操作字串工具包中不可或缺的一部分。 透過瞭解如何有效使用此方法,您可以輕鬆修改 C# 應用程式中的字串值,以滿足各種程式設計需求。

IronPDF 提供免費試用和許可信息,其許可證從 $999 開始。 此工具可進一步增強您在 .NET 應用程式中處理 PDF 文件的能力。

常見問題解答

如何在 C# 中替換字串中的字元?

您可以使用 C# 的 String 類別的 Replace 方法來替換字串中的字元。此方法允許您指定要替換的字元和將取而代之的新字元,並返回具有指定更改的新字串。

在 C# 中替換字元和子字串有什麼區別?

在 C# 中替換字元涉及使用具有字元參數的 Replace 方法來更改單個字元,而替換子字串則涉及使用相同方法的字串參數來更改字元序列。這兩種操作都會返回應用更改的新字串。

我可以在 C# 中在一個語句中執行多次替換嗎?

是的,您可以通過鏈接 Replace 方法調用在 C# 中的一個語句中執行多次替換。這允許您在相同字串中連續替換多個字元或子字串。

如何在 .NET 應用程式中從 HTML 生成 PDF?

您可以使用 IronPDF 庫在 .NET 應用程式中從 HTML 生成 PDF。它提供了像 RenderHtmlAsPdf 這樣的方法來將 HTML 字串轉換為 PDF 或 RenderHtmlFileAsPdf 將 HTML 文件轉換為 PDF 文件,同時確保保留版面和格式。

Replace 方法可以用於 HTML 到 PDF 的轉換嗎?

可以,Replace 方法可以用來替換佔位符為動態資料以修改 HTML 內容,然後使用像 IronPDF 這樣的庫將 HTML 轉換為 PDF。這對於生成如發票或報告般的動態內容非常有用。

C# 中的 Replace 方法是區分大小寫的嗎?

C# 中的 Replace 方法是區分大小寫的。若要執行不區分大小寫的替換,您可能需要在應用替換之前使用 ToLowerToUpper 等方法調整字串的大小寫。

C# 中 Replace 方法的一些高級用法是什麼?

C# 中 Replace 方法的高級用法包括在一次語句中執行多次替換、通過修改字串的大小寫來處理大小寫敏感性、以及用空字串替換以有效地刪除字元或子字串。

如何在 PDF 生成中動態替換 HTML 模板中的佔位符?

您可以使用 Replace 方法動態地在 HTML 模板中替換佔位符,以便在將其轉換為 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 小時在線上。
聊天
電子郵件
打電話給我