Split string into array of character strings

JavaRegexSplit

Java Problem Overview


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

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

Java Solutions


Solution 1 - Java

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

This will produce > array ["c", "a", "t"]

Solution 2 - Java

"cat".toCharArray()

But if you need strings

"cat".split("")

Edit: which will return an empty first value.

Solution 3 - Java

String str = "cat";
char[] cArray = str.toCharArray();

Solution 4 - Java

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

"a💫b".codePoints()
    .mapToObj(cp -> new String(Character.toChars(cp)))
    .toArray(size -> new String[size]);

Solution 5 - Java

split("(?!^)") does not work correctly if the string contains surrogate pairs. You should use split("(?<=.)").

String[] splitted = "花ab🌹🌺🌷".split("(?<=.)");
System.out.println(Arrays.toString(splitted));

output:

[花, a, b, 🌹, 🌺, 🌷]

Solution 6 - Java

To sum up the other answers...

This works on all Java versions:

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

This only works on Java 8 and up:

"cat".split("")

Solution 7 - Java

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.

Solution 8 - Java

for(int i=0;i<str.length();i++)
{
System.out.println(str.charAt(i));
}

Solution 9 - Java

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.

Solution 10 - Java

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);
}

Solution 11 - Java

We can do this simply by

const string = 'hello';
console.log([...string]); // -> ['h','e','l','l','o']

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax says

> Spread syntax (...) allows an iterable such as an array expression or string to be expanded...

So, strings can be quite simply spread into arrays of characters.

Solution 12 - Java

In my previous answer I mixed up with JavaScript. Here goes an analysis of performance in Java.

I agree with the need for attention on the Unicode Surrogate Pairs in Java String. This breaks the meaning of methods like String.length() or even the functional meaning of Character because it's ultimately a technical object which may not represent one character in human language.

I implemented 4 methods that split a string into list of character-representing strings (Strings corresponding to human meaning of characters). And here's the result of comparison:

A line is a String consisting of 1000 arbitrary chosen emojis and 1000 ASCII characters (1000 times <emoji><ascii>, total 2000 "characters" in human meaning).

Comparison of different splitting methods

(discarding 256 and 512 measures) enter image description here

Implementations:

  • codePoints (java 11 and above)
    public static List<String> toCharacterStringListWithCodePoints(String str) {
        if (str == null) {
            return Collections.emptyList();
        }
        return str.codePoints()
            .mapToObj(Character::toString)
            .collect(Collectors.toList());
    }
  • classic
    public static List<String> toCharacterStringListWithIfBlock(String str) {
        if (str == null) {
            return Collections.emptyList();
        }
        List<String> strings = new ArrayList<>();
        char[] charArray = str.toCharArray();
        int delta = 1;
        for (int i = 0; i < charArray.length; i += delta) {
            delta = 1;
            if (i < charArray.length - 1 && Character.isSurrogatePair(charArray[i], charArray[i + 1])) {
                delta = 2;
                strings.add(String.valueOf(new char[]{ charArray[i], charArray[i + 1] }));
            } else {
                strings.add(Character.toString(charArray[i]));
            }
        }
        return strings;
    }
  • regex
    static final Pattern p = Pattern.compile("(?<=.)");
    public static List<String> toCharacterStringListWithRegex(String str) {
        if (str == null) {
            return Collections.emptyList();
        }
        return Arrays.asList(p.split(str));
    }

Annex (RAW DATA):

codePoints;classic;regex;lines
45;44;84;256
14;20;98;512
29;42;91;1024
52;56;99;2048
87;121;174;4096
175;221;375;8192
345;411;839;16384
667;826;1285;32768
1277;1536;2440;65536
2426;2938;4238;131072

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMattView Question on Stackoverflow
Solution 1 - JavacobertyView Answer on Stackoverflow
Solution 2 - JavaYuriy FaktorovichView Answer on Stackoverflow
Solution 3 - JavaRamanView Answer on Stackoverflow
Solution 4 - JavaJan MolnarView Answer on Stackoverflow
Solution 5 - Javauser4910279View Answer on Stackoverflow
Solution 6 - JavaLezorteView Answer on Stackoverflow
Solution 7 - JavaStephen CView Answer on Stackoverflow
Solution 8 - JavaJV MoreView Answer on Stackoverflow
Solution 9 - JavareefView Answer on Stackoverflow
Solution 10 - JavaDaniel NitzanView Answer on Stackoverflow
Solution 11 - JavaMasaru TomimitsuView Answer on Stackoverflow
Solution 12 - JavaMasaru TomimitsuView Answer on Stackoverflow