在Java中寻找快速、简单的方法来更改此字符串
" hello there "
变成了这样的东西
"hello there"
在这里我用一个空格替换了所有这些多个空格,除了我还希望字符串开头的一个或多个空格消失。
像这样的事情能让我在一定程度上做到
String mytext = " hello there ";
mytext = mytext.replaceAll("( )+", " ");
但事实并非如此。
在Java中寻找快速、简单的方法来更改此字符串
" hello there "
变成了这样的东西
"hello there"
在这里我用一个空格替换了所有这些多个空格,除了我还希望字符串开头的一个或多个空格消失。
像这样的事情能让我在一定程度上做到
String mytext = " hello there ";
mytext = mytext.replaceAll("( )+", " ");
但事实并非如此。
当前回答
请使用以下代码
package com.myjava.string;
import java.util.StringTokenizer;
public class MyStrRemoveMultSpaces {
public static void main(String a[]){
String str = "String With Multiple Spaces";
StringTokenizer st = new StringTokenizer(str, " ");
StringBuffer sb = new StringBuffer();
while(st.hasMoreElements()){
sb.append(st.nextElement()).append(" ");
}
System.out.println(sb.toString().trim());
}
}
其他回答
下面的代码将压缩单词之间的空白,并删除字符串开头和结尾的空白
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类的文档
你好,抱歉耽搁了! 以下是你正在寻找的最佳和最有效的答案:
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();
你只需要:
replaceAll("\\s{2,}", " ").trim();
你可以匹配一个或多个空格,用一个空格替换它们,然后在开头和结尾修剪空白(你实际上可以通过先修剪然后匹配来反转正则表达式,就像有人指出的那样)。
要快速测试,请尝试:
System.out.println(new String(" hello there ").trim().replaceAll("\\s{2,}", " "));
它会返回:
"hello there"
如果你已经在你的项目中使用了Guava(19+节),你可能想要使用这个:
CharMatcher.whitespace().trimAndCollapseFrom(input, ' ');
或者,如果你需要删除空格符号(或U+0020,查看更多空白),使用:
CharMatcher.anyOf(" ").trimAndCollapseFrom(input, ' ');
"[ ]{2,}"
这将匹配多个空格。
String mytext = " hello there ";
//without trim -> " hello there"
//with trim -> "hello there"
mytext = mytext.trim().replaceAll("[ ]{2,}", " ");
System.out.println(mytext);
输出:
hello there