String test=" Begin with spaces";
for(String n:test.split("\\s"))
System.out.println(n);
输出结果为:
开始
与
空间
我想删除所有空格,但它会创建空字符串。我最初不能使用修剪,那么这个问题的最佳解决方案是什么?
答案 0 :(得分:1)
如果你想要输出:
开始
与
空间
然后我将使用的代码是:
String test = "Begin with spaces";
for(String n:test.split(" "))
System.out.println(n);
所以只需尝试使用“”代替/ s
如果你想把它们扔进一个字符串就行了:
String str = "";
String test = "Begin with spaces"
for(String n:test.split(" "))
str = str+n;
System.out.println(str);
答案 1 :(得分:1)
内置的String.split
方法真的很疯狂。听起来你最好使用Guava's Splitter
:
Iterable<String> strings = Splitter
.on(CharMatcher.WHITESPACE)
.trimResults()
.omitEmptyStrings()
.split(myString);
答案 2 :(得分:0)
org.apache.commons.lang.StringUtils.split(" Begin with spaces", null);
返回:
["Begin", "with", "spaces"]