我正在编写以下程序来从字符串中分离字符并将其分配给数组。
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
我得到一个空字符串作为数组的第一个元素。我期望输出没有空字符串,字符数组的长度为 5 而不是 6。为什么拆分此字符串后会出现空字符?
最佳答案
您可以使用 String#toCharArray()
方法:
String str = "hello";
char[] arr = str.toCharArray();
至于你的问题,当你拆分一个空字符串时,你会得到第一个元素作为空字符串,因为,你的字符串以一个空字符串开头,并且在每个字符之后也是一个空字符串。
因此,第一次拆分发生在第一个字符之前。
h e l l o
^ ^ ^ ^ ^ ^
"Split location"
尾随的空字符串被丢弃,如 documentation 中指定的那样:
Trailing empty strings are therefore not included in the resulting array.
关于java - 从字符串中拆分单个字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17411747/