Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
147 views
in Technique[技术] by (71.8m points)

java - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...