Apex開発で文字列内に特定の値を差し込みしたいというケースがあると思います。キーワードを決めてreplace処理で対応することもできますが、Stringクラスのformat関数をつかうことでより簡単に対応できます。
置換したい箇所は「{0} {1} {2} ...」というように宣言します。置換後の文字列はList型で用意します。
String placeholder = 'Hello {0}, {1} is cool!'; List<String> fillers = new String[]{'Jason','Apex'}; String formatted = String.format(placeholder, fillers); System.assertEquals('Hello Jason, Apex is cool!', formatted);
サンプルです。
実行結果はこんな感じ。
{0},{1}と用意して{0}は使わないというような処理でもエラーにならずに実行できます。
String placeholder = 'Hello {1} is cool!'; List<String> fillers = new String[]{'Jason', 'Apex'}; String formatted = String.format(placeholder, fillers); // "Hello Apex is cool!"となります。
文字列内に値を動的に差し込みたいときはformat関数が便利です。