在Java中寻找快速、简单的方法来更改此字符串
" hello there "
变成了这样的东西
"hello there"
在这里我用一个空格替换了所有这些多个空格,除了我还希望字符串开头的一个或多个空格消失。
像这样的事情能让我在一定程度上做到
String mytext = " hello there ";
mytext = mytext.replaceAll("( )+", " ");
但事实并非如此。
在Java中寻找快速、简单的方法来更改此字符串
" hello there "
变成了这样的东西
"hello there"
在这里我用一个空格替换了所有这些多个空格,除了我还希望字符串开头的一个或多个空格消失。
像这样的事情能让我在一定程度上做到
String mytext = " hello there ";
mytext = mytext.replaceAll("( )+", " ");
但事实并非如此。
当前回答
流版本,过滤空格和制表符。
Stream.of(str.split("[ \\t]")).filter(s -> s.length() > 0).collect(Collectors.joining(" "))
其他回答
"[ ]{2,}"
这将匹配多个空格。
String mytext = " hello there ";
//without trim -> " hello there"
//with trim -> "hello there"
mytext = mytext.trim().replaceAll("[ ]{2,}", " ");
System.out.println(mytext);
输出:
hello there
你好,抱歉耽搁了! 以下是你正在寻找的最佳和最有效的答案:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class MyPatternReplace {
public String replaceWithPattern(String str,String replace){
Pattern ptn = Pattern.compile("\\s+");
Matcher mtch = ptn.matcher(str);
return mtch.replaceAll(replace);
}
public static void main(String a[]){
String str = "My name is kingkon. ";
MyPatternReplace mpr = new MyPatternReplace();
System.out.println(mpr.replaceWithPattern(str, " "));
}
所以这个例子的输出将是: 我的名字叫金康。
然而,这个方法也会删除你的字符串可能有的“\n”。如果你不想这样,就用这个简单的方法:
while (str.contains(" ")){ //2 spaces
str = str.replace(" ", " "); //(2 spaces, 1 space)
}
如果你也想去掉开头和结尾的空格,只需添加:
str = str.trim();
使用Apache commons StringUtils。normalizeSpace(String str)方法。点击这里查看文档
String str = " this is string ";
str = str.replaceAll("\\s+", " ").trim();
我的方法之前,我发现第二个答案使用正则表达式作为一个更好的解决方案。也许有人需要这个代码。
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();
}