Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
138 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 Reply

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...