Advertisement
Advertisement


Split string into array of character strings


Question

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

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

2017/12/02
1
115
12/2/2017 11:07:13 PM

Accepted Answer

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

This will produce

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

2012/10/19
121
10/19/2012 7:39:40 AM


String str = "cat";
char[] cArray = str.toCharArray();
2011/03/08

If characters beyond Basic Multilingual Plane are expected on input (some CJK characters, new emoji...), approaches such as "ab".split("(?!^)") cannot be used, because they break such characters (results into array ["a", "?", "?", "b"]) and something safer has to be used:

"ab".codePoints()
    .mapToObj(cp -> new String(Character.toChars(cp)))
    .toArray(size -> new String[size]);
2017/02/18

To sum up the other answers...

This works on all Java versions:

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

This only works on Java 8 and up:

"cat".split("")
2018/03/06

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.

2017/01/27

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.

2011/03/08

Source: https://stackoverflow.com/questions/5235401
Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Email: [email protected]