2013/07/30 (Tue)
アンダースコア区切りの文字列をキャメルケースに変換
java |
最近のguava-libraries*1だと、一行でできるんですね。
以前 g:program:id:halflite:20101207:camel の"THIS_IS_AN_EXAMPLE_STRING"→"ThisIsAnExampleString"の例だと以下のように。
@Test public void testToCamel() { String camel = CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.UPPER_CAMEL, "THIS_IS_AN_EXAMPLE_STRING"); assertThat(camel, is("ThisIsAnExampleString")); }
static importを使うと、もっと短くなりますかね。
import static com.google.common.base.CaseFormat.*;
アンダースコア区切り(所謂「スネークケース」)は、こんな感じで。
@Test public void testToLowerSnakeCese() { String snake = LOWER_UNDERSCORE.to(LOWER_CAMEL, "thisIsAnExampleString"); assertThat(snake, is("this_is_an_example_string")); }
*1:手元の環境だと、version 14.0.1
コメント
トラックバック - http://program.g.hatena.ne.jp/halflite/20130730