.NET ヘルプ

C# 文字列置換 (開発者のための動作方法)

更新済み 5月 16, 2023
共有:

プログラミングを始めたばかりの方や、C#での文字列操作についてより理解を深めたい方にとって、ここは最適な場所です。 このチュートリアルでは、親しみやすい実生活の例とストーリーテリングを用いて、C# の replace メソッドを探求し、わかりやすくて楽しい内容にしていきます。

基本情報 文字列とは何ですか?

「string replace」メソッドに入る前に、まず文字列の基本について探りましょう。 文字列とは、文字、数字、記号を含む一連の文字のことです。 C# では、文字列は string データ型で表されます。 それらはプログラムでテキストを扱うために不可欠であり、テキストを操作するための多数の組み込みメソッドが用意されています。 その方法の一つが「replace」メソッドであり、このチュートリアルではそれに焦点を当てます。

置換メソッドのご紹介

想像してみてください、ユーザーに文章を入力させるアプリケーションを書いているとします。 アプリケーションは、特定の単語や文字を新しいものに置き換える必要があります。 ここでC#のreplaceメソッドが役立ちます。

replaceメソッドは、指定されたUnicode文字またはサブストリングのすべての出現を新しい文字列で置き換えることを可能にする組み込み関数です。 次のような文字列があるとしましょう。「I love ice cream.」この中の「ice」という単語を「chocolate」に置き換えて、新しい文字列「I love chocolate cream.」を作りたい場合、replaceメソッドを使えば、この作業は簡単かつ効率的に行えます。

置換メソッドの使用 ステップバイステップガイド

置換メソッドを使用するには、以下の簡単な手順に従ってください:

  1. 元のテキストを含む文字列変数を宣言します。

  2. 指定された文字列に対して replace メソッドを呼び出し、置き換える文字または部分文字列と新しい文字列を指定します。

    1. 以下の内容を日本語に翻訳します:

新しい文字列変数に結果を保存するか、元の文字列を更新します。

次の手順を示すコード例を示します:

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)
VB   C#

このコードスニペットは、変更された文字列を出力します: "I love chocolate cream."

リプレースメソッドの異なるバリエーション

C# には、さまざまなニーズに応えるためにオーバーロードされた2つの replace メソッドのバージョンがあります。 それらを詳しく見てみましょう:

指定されたUnicode文字を置換する

置換メソッドの最初のバージョンでは、指定されたUnicode文字を新しい文字に置き換えることができます。 このバージョンの構文は次の通りです:

public string Replace(char oldChar, char newChar);
public string Replace(char oldChar, char newChar);
public String Replace(Char oldChar, Char newChar)
VB   C#

使用例をご紹介します:

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)
VB   C#

出力は: "Hello World"!"

サブストリングの置換

replaceメソッドの第2バージョンでは、指定されたサブストリングを新しい文字列に置き換えることができます。 このバージョンの構文は次の通りです:

public string Replace(string oldValue, string newValue);
public string Replace(string oldValue, string newValue);
public String Replace(String oldValue, String newValue)
VB   C#

使用例をご紹介します:

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)
VB   C#

出力は、このようになります:「私は青い車と青い帽子を持っています。」

ケース感度とReplaceメソッド

重要な点として、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)
VB   C#

出力はこうなるでしょう:「猫は素晴らしいペットですが、犬を好む人もいます。」

「CATS」という大文字の部分のみが置き換えられ、小文字の「Cats」はそのまま残っています。 大文字と小文字を区別しない置換を実行したい場合は、元の文字列と検索文字列を共通の大文字または小文字に変換する必要があります。 (いずれか上か下) そして、置換を実行します。 Here's an example: 例があります。

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)
VB   C#

出力は次のようになります:「犬は素晴らしいペットですが、中には犬を好む人もいます。」

ご注意ください、このアプローチにより文字列全体の大文字小文字も変更されます。 元の大文字小文字を保持したい場合は、RegexOptions.IgnoreCaseフラグを使用してRegex.Replaceメソッドを使用できます。

置換メソッドを連鎖する力

複数の置換メソッドを連結することも可能で、1行のコードで複数の置換処理を実行できます。 これは、複数の文字や部分文字列を異なる新しい文字列に置き換える必要がある場合に特に有用です。 Here's an example: 例があります。

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)
VB   C#

出力は: "Hello World"!"

この例では、1行のコードを使用して '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)
VB   C#

出力は、「たくさんの猫、たくさんの犬、そしてたくさんの鳥」となります。

この例では、正規表現パターン \d+ を使用して1文字以上の数字のシーケンスに一致させ、それを「many」という単語で置き換えました。

IronPDF: C#で文字列置換を使用したPDF生成

IronPDFの強力な能力を活用することができます。 HTMLからPDF C#のstring replaceメソッドと連携した変換機能によって、動的な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
VB   C#

IronPDF の始め方

使用を開始するには IronPDFまず、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 replaceメソッドを使用して、現在の文字列とプレースホルダーを実際のユーザーデータに置き換えます。

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")
VB   C#

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)
VB   C#

PDFドキュメントをファイルに保存するか、ユーザーにストリーミングします。

pdfDocument.SaveAs("PersonalizedGreeting.PDF");
pdfDocument.SaveAs("PersonalizedGreeting.PDF");
pdfDocument.SaveAs("PersonalizedGreeting.PDF")
VB   C#

C# 文字列置換 (開発者向けの仕組み) 図 1 - 出力

以上です! C#のreplaceメソッドとIronPDFを使用して、個別のPDFドキュメントを作成しました。

結論

IronPDF のパワーと C# の replace メソッドの柔軟性を組み合わせることで、特定のユーザーやシナリオに合わせた動的な PDF ドキュメントを作成することができます。 このアプローチは個別の挨拶に限ったものではありません。請求書、報告書、証明書など、さまざまなものの生成に使用できます。

IronPDFは 無料試用最初の投資なしでその機能を探求することができます。 PDF生成のニーズに完璧に合っていると感じた場合、ライセンスは$Lite Licenseから始まります。

< 以前
C#のForループ(開発者向けの動作方法)
次へ >
C# For Each(開発者向けの仕組み)

準備はできましたか? バージョン: 2024.9 新発売

無料のNuGetダウンロード 総ダウンロード数: 10,659,073 View Licenses >