まとめ
Javaの標準APIで実現できる。
java.text.BreakIterator.getCharacterInstance()
を使用すればよい。
なお、以下の文章における「文字」という語は、「書記素クラスター」(grapheme clusters) を意味している。
要件
(参考) BreakIterator
による、文字列→文字への分解 ※無保証
public static List<String> graphemeClusters(String str) {
final List<String> result = new ArrayList<String>(str.length());
final BreakIterator breakIterator = BreakIterator.getCharacterInstance();
breakIterator.setText(str);
int start = breakIterator.first();
int end = breakIterator.next();
while (end != BreakIterator.DONE) {
result.add(str.substring(start, end));
start = end;
end = breakIterator.next();
}
return result;
}
/* 実行結果
graphemeClusters("abc")
= [ |
"a", |
"b", |
"c" |
] |
= [ |
\u0061, |
\u0062, |
\u0063 |
] |
graphemeClusters("あいう")
= [ |
"あ", |
"い", |
"う" |
] |
= [ |
\u3042, |
\u3044, |
\u3046 |
] |
graphemeClusters("𠮷野家")
= [ |
"𠮷", |
"野", |
"家" |
] |
= [ |
\ud842 \udfb7, |
\u91ce, |
\u5bb6 |
] |
graphemeClusters("葛󠄁飾区")
= [ |
"葛󠄁", |
"飾", |
"区" |
] |
= [ |
\u845b \udb40 \udd01, |
\u98fe, |
\u533a |
] |
graphemeClusters("Åström")
= [ |
"Å", |
"s", |
"t", |
"r", |
"ö", |
"m" |
] |
= [ |
\u0041 \u030a, |
\u0073, |
\u0074, |
\u0072, |
\u006f \u0308, |
\u006d |
] |
graphemeClusters("ạ̭̈̃")
= [ |
"ạ̭̈̃" |
] |
= [ |
\u0061 \u0308 \u0303 \u0323 \u032d |
] |
*/
参考