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:46
"cat".split("(?!^)")

This will produce

array ["c", "a", "t"]

查看更多
只靠听说
3楼-- · 2019-01-01 13:46
"cat".toCharArray()

But if you need strings

"cat".split("")

Edit: which will return an empty first value.

查看更多
与君花间醉酒
4楼-- · 2019-01-01 13:46
String str = "cat";
char[] cArray = str.toCharArray();
查看更多
春风洒进眼中
5楼-- · 2019-01-01 13:54

An efficient way of turning a String into an array of one-character Strings would be to do this:

String[] res = new String[str.length()];
for (int i = 0; i < str.length(); i++) {
    res[i] = Character.toString(str.charAt(i));
}

However, this does not take account of the fact that a char in a String could actually represent half of a Unicode code-point. (If the code-point is not in the BMP.) To deal with that you need to iterate through the code points ... which is more complicated.

This approach will be faster than using String.split(/* clever regex*/), and it will probably be faster than using Java 8+ streams. It is probable faster than this:

String[] res = new String[str.length()];
int 0 = 0;
for (char ch: str.toCharArray[]) {
    res[i++] = Character.toString(ch);
}  

because toCharArray has to copy the characters to a new array.

查看更多
登录 后发表回答