tyoshikawa1106のブログ

- Force.com Developer Blog -

SFDC:Stringクラスのformat関数について

Apex開発で文字列内に特定の値を差し込みしたいというケースがあると思います。キーワードを決めてreplace処理で対応することもできますが、Stringクラスのformat関数をつかうことでより簡単に対応できます。

f:id:tyoshikawa1106:20160627155204p:plain

Salesforce Developers


置換したい箇所は「{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);


サンプルです。


実行結果はこんな感じ。
f:id:tyoshikawa1106:20160627161120p:plain


{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関数が便利です。