Split string into array of character strings

2019-01-01 13:09发布

I need to split a String into an array of single character Strings.

Eg, splitting "cat" would give the array "c", "a", "t"

标签: java regex split
10条回答
路过你的时光
2楼-- · 2019-01-01 13:28

Maybe you can use a for loop that goes through the String content and extract characters by characters using the charAt method.

Combined with an ArrayList<String> for example you can get your array of individual characters.

查看更多
闭嘴吧你
3楼-- · 2019-01-01 13:30

If characters beyond Basic Multilingual Plane are expected on input (some CJK characters, new emoji...), approaches such as "a

查看更多
临风纵饮
4楼-- · 2019-01-01 13:33

Take a look at the String class's getChars() method.

查看更多
人间绝色
5楼-- · 2019-01-01 13:34

If the original string contains supplementary Unicode characters, then split() would not work, as it splits these characters into surrogate pairs. To correctly handle these special characters, a code like this works:

String[] chars = new String[stringToSplit.codePointCount(0, stringToSplit.length())];
for (int i = 0, j = 0; i < stringToSplit.length(); j++) {
    int cp = stringToSplit.codePointAt(i);
    char c[] = Character.toChars(cp);
    chars[j] = new String(c);
    i += Character.charCount(cp);
}
查看更多
骚的不知所云
6楼-- · 2019-01-01 13:38
for(int i=0;i<str.length();i++)
{
System.out.println(str.charAt(i));
}
查看更多
笑指拈花
7楼-- · 2019-01-01 13:44

To sum up the other answers...

This works on all Java versions:

"cat".split("(?!^)")

This only works on Java 8 and up:

"cat".split("")
查看更多
登录 后发表回答