[C#]replaceで置換回数を指定して文字列を抽出する!

アイキャッチC#
広告

C#において、文字列から指定した回数だけ置換を行い、その結果を抽出する方法を学びましょう。

この方法を使用することで、特定の部分だけを一度だけでなく、

複数回置換した結果を得ることができます。

広告

replaceで置換回数を指定して文字列を抽出する

以下のサンプルコードでは、Replaceメソッドを使用して指定回数だけ文字列の置換を行います。

具体的には、指定回数だけ特定の文字列を置換し、その結果を抽出しています。

using System;

class Program
{
    static void Main()
    {
        string inputString = "apple, orange, banana, apple, cherry, apple";
        string targetSubstring = "apple";
        int replaceCount = 2; // 置換回数

        // 指定回数だけ置換を行い、その結果を抽出
        string resultString = ReplaceAndExtract(inputString, targetSubstring, replaceCount);

        Console.WriteLine($"Original String: {inputString}");
        Console.WriteLine($"Result String  : {resultString}");
    }

    static string ReplaceAndExtract(string input, string target, int count)
    {
        int currentIndex = -1;

        for (int i = 0; i < count; i++)
        {
            currentIndex = input.IndexOf(target, currentIndex + 1);

            if (currentIndex == -1)
                break;

            input = input.Remove(currentIndex, target.Length).Insert(currentIndex, "***"); 
       // 仮の置換文字列 "***" を挿入
        }

        // 仮の置換文字列 "***" を元の文字列に戻す
        return input.Replace("***", target);
    }
}

このコードでは、指定回数だけ targetSubstring(ここでは “apple”)を置換しその結果を抽出しています。

ReplaceAndExtractメソッド内で IndexOfメソッドを使用して、

指定回数だけ目標の部分を検索し、RemoveメソッドとInsertメソッドを使用して置換を行っています。

まとめ

まとめ

この記事では、C#で指定した回数だけReplaceで置換して抽出する方法について解説しました。

指定回数の置換を行うことで、特定の部分を複数回処理した結果を得ることができます。

C#
広告
広告
塩竈Code
タイトルとURLをコピーしました