Split string into character array

I need to split String into an array of strings with one character.

For example, splitting "cat" will give an array of "c", "a", "t"

+79
java split regex
Mar 08 '11 at 16:38
source share
8 answers
"cat".split("(?!^)") 

This will create

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

+92
Oct 19 '12 at 7:35
source share
— -
 "cat".toCharArray() 

But if you need strings

 "cat".split("") 

Edit: this will return an empty first value.

+78
Mar 08 '11 at 16:40
source share
 String str = "cat"; char[] cArray = str.toCharArray(); 
+32
Mar 08 2018-11-11T00:
source share

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

+4
Mar 08 '11 at 16:40
source share

An efficient way to turn String into an array of single-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 into account the fact that a char in String can actually represent half the Unicode code point. (If the code point is not in BMP.) To deal with this, 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+ threads. Most likely this is faster:

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

because toCharArray must copy the characters into a new array.

+1
Jan 27 '17 at 8:03 on
source share

If the input contains characters outside the Basic Multilingual Plane (some CJK characters, new emoji ...), approaches like "a💫b".split("(?!^)") Cannot be used because they break such characters (results on array ["a", "?", "?", "b"] ), and you need to use something more secure:

 "a💫b".codePoints() .mapToObj(cp -> new String(Character.toChars(cp))) .toArray(size -> new String[size]); 
+1
Feb 18 '17 at 14:41
source share

Perhaps you can use a for loop that goes through the contents of the String, and extract characters with characters using the charAt method.

In combination with ArrayList<String> , for example, you can get your array of individual characters.

-one
Mar 08 '11 at 16:40
source share
 for(int i=0;i<str.length();i++) { System.out.println(str.charAt(i)); } 
-2
Jun 07 '16 at 16:55
source share