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.
This will produce
But if you need strings
Edit: which will return an empty first value.
An efficient way of turning a String into an array of one-character Strings would be to do this:
However, this does not take account of the fact that a
char
in aString
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:because
toCharArray
has to copy the characters to a new array.