Append, AppendLine, AppendFormat, Insert, Remove, Replaceの各メソッドは、戻り値としてインスタンス自身を返します。 これにより、stringクラスと同様にメソッドチェインを記述出来ます。
StringとStringBuilderで、メソッドチェインによって文字列操作を連結する
using System;
using System.Text;
class Sample {
static void Main()
{
var s = "The quick brown fox jumps over the lazy dog";
var sb = new StringBuilder("The quick brown fox jumps over the lazy dog");
Console.WriteLine("String : <{0}>", s);
Console.WriteLine("StringBuilder: <{0}>", sb);
s = s.Remove(4, 6).Remove(29, 4).Insert(29, "3").Insert(30, " white").Replace("dog", "dogs").Replace('o', 'a').Replace("brawn ", null);
sb = sb.Remove(4, 6).Remove(29, 4).Insert(29, 3 ).Insert(30, " white").Replace("dog", "dogs").Replace('o', 'a').Replace("brawn ", null);
Console.WriteLine("String : <{0}>", s);
Console.WriteLine("StringBuilder: <{0}>", sb);
}
}
実行結果
String : <The quick brown fox jumps over the lazy dog> StringBuilder: <The quick brown fox jumps over the lazy dog> String : <The fax jumps aver the 3 white dags> StringBuilder: <The fax jumps aver the 3 white dags>