2009/10/05(Mon) 21:04:22 編集(投稿者)
■No41966 (ド素党 さん) に返信
> bcがXYZに何箇所置き換わったか数はわかるのでしょうか?
> string abc = "abcabcabcabcabcabc";
> abc = abc.Replace("bc", "XYZ");
> Console.WriteLine(abc);
string source = "abcabcabcabcabcabc";
string oldText = "bc";
string newText = "XYZ";
// 案1
string text1 = source.Replace(oldText, newText);
int count1 = source.Replace(oldText, oldText + "\0").Length - source.Length;
Console.WriteLine("{0}個置換しました:[{1}]", count1, text1);
// 案2
// Regex reg = new Regex(oldText);
// string text2 = reg.Replace(source, newText);
Regex reg = new Regex(Regex.Escape(oldText));
string text2 = reg.Replace(source, newText.Replace("$", "$$"));
int count2 = reg.Matches(source).Count;
Console.WriteLine("{0}個置換しました:[{1}]", count2, text2);