从字符串中分割单个字符 [英] 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]);
}
}
}
我得到的输出是:
0:
1:h
2:e
3:l
4:l
5:o
我得到一个空字符串作为数组的第一个元素.我期望输出没有空字符串,而chars数组的长度是5而不是6.为什么拆分此String后会出现空char?
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?
推荐答案
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"