文字列を置換する。置換回数を指定する

string クラスの Replace メソッドによる文字列の置換は、マッチする全ての文字列が置換されます。

$ csharp
Mono C# Shell, type "help;" for help

Enter statements below.
csharp> var s = "abc abc abc";
csharp> s.Replace("abc", "def");
"def def def"

上のように、文字列 s の abc が全て def に置き換わっています。 はじめの abc のみ def に置き換えたいときには、部分文字列を取り出す方法もありますが、 Regex クラスの Replace メソッドを使うと簡単です。

csharp> using System.Text.RegularExpressions;
csharp> var re = new Regex("abc");
csharp> re.Replace(s, "def", 1);
"def abc abc"
csharp> re.Replace(s, "def", 2);
"def def abc"
csharp> re.Replace(s, "def", 3);
"def def def"