在Java中寻找快速、简单的方法来更改此字符串
" hello there "
变成了这样的东西
"hello there"
在这里我用一个空格替换了所有这些多个空格,除了我还希望字符串开头的一个或多个空格消失。
像这样的事情能让我在一定程度上做到
String mytext = " hello there ";
mytext = mytext.replaceAll("( )+", " ");
但事实并非如此。
在Java中寻找快速、简单的方法来更改此字符串
" hello there "
变成了这样的东西
"hello there"
在这里我用一个空格替换了所有这些多个空格,除了我还希望字符串开头的一个或多个空格消失。
像这样的事情能让我在一定程度上做到
String mytext = " hello there ";
mytext = mytext.replaceAll("( )+", " ");
但事实并非如此。
当前回答
我的方法之前,我发现第二个答案使用正则表达式作为一个更好的解决方案。也许有人需要这个代码。
private String replaceMultipleSpacesFromString(String s){
if(s.length() == 0 ) return "";
int timesSpace = 0;
String res = "";
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if(c == ' '){
timesSpace++;
if(timesSpace < 2)
res += c;
}else{
res += c;
timesSpace = 0;
}
}
return res.trim();
}
其他回答
这是删除字符串中任何空白的最简单方法。
public String removeWhiteSpaces(String returnString){
returnString = returnString.trim().replaceAll("^ +| +$|( )+", " ");
return returnString;
}
流版本,过滤空格和制表符。
Stream.of(str.split("[ \\t]")).filter(s -> s.length() > 0).collect(Collectors.joining(" "))
下面的代码将压缩单词之间的空白,并删除字符串开头和结尾的空白
String input = "\n\n\n a string with many spaces, \n"+
" a \t tab and a newline\n\n";
String output = input.trim().replaceAll("\\s+", " ");
System.out.println(output);
这将输出一个包含许多空格、制表符和换行符的字符串
注意,任何不可打印的字符,包括空格、制表符和换行符将被压缩或删除
欲了解更多信息,请参阅相应的文档:
字符串#修剪()方法 String#replaceAll(字符串正则表达式,字符串替换)方法 有关Java正则表达式实现的信息,请参阅Pattern类的文档
可以使用字符串标记器
String str = " hello there ";
StringTokenizer stknzr = new StringTokenizer(str, " ");
StringBuffer sb = new StringBuffer();
while(stknzr.hasMoreElements())
{
sb.append(stknzr.nextElement()).append(" ");
}
System.out.println(sb.toString().trim());
在Kotlin中是这样的
val input = "\n\n\n a string with many spaces, \n"
val cleanedInput = input.trim().replace(Regex("(\\s)+"), " ")