Jainendra
Jainendra

Reputation: 25143

Split individual characters from a string

I'm writing following program to separate characters from a string and assign it to an array.

public class Str {
    public static void main(String[] args) {
        String str = "hello";
        String[] chars = str.split("");
        for (int i = 0; i < chars.length; i++) {
            System.out.println(i + ":" + chars[i]);
        }
    }
}

The output I'm getting is:

0:
1:h
2:e
3:l
4:l
5:o

I'm getting an empty string as the first element of the array. I was expecting the output to be without empty string and the length of chars array to be 5 instead of 6. Why empty char is coming after splitting this String?

Upvotes: 1

Views: 638

Answers (3)

JHS
JHS

Reputation: 7871

Have you tried the toCharArray() method from the String class.

The issue with splitting the String with this "" is that "" matches the first character in the string and therefore you get an empty character.

To verify this claim. You could try str.indexOf(""). This would give you a value 0. If the argument does not occur as a substring, -1 is returned, according to the documentation.

Upvotes: 4

srikanta
srikanta

Reputation: 2999

Like others have noted, using toCharArray() is the preferred method to do this kind of operation. Since the OP wants to know why the first string is empty when using split(""), it is because empty string is the first match even before the 1st character is parsed. As per documentation, only trailing empty strings are ignored and not the leading empty strings.

In order to work around this problem you can use negative look behind. So, to use split and ignore the first empty string your regex should be:

str.split("(?<!^)")

Upvotes: 1

Rohit Jain
Rohit Jain

Reputation: 213193

You can use String#toCharArray() method:

String str = "hello";
char[] arr = str.toCharArray();

As for your question, when you split on an empty string, you will get the first element as empty string, because, your string starts with an empty string, and after every character also, there is an empty string.

So, the first split occurs before the first character.

 h e l l o
^ ^ ^ ^ ^ ^
"Split location"

The trailing empty strings are discarded, as specified in documentation:

Trailing empty strings are therefore not included in the resulting array.

Upvotes: 7

Related Questions