在Java中寻找快速、简单的方法来更改此字符串

" hello     there   "

变成了这样的东西

"hello there"

在这里我用一个空格替换了所有这些多个空格,除了我还希望字符串开头的一个或多个空格消失。

像这样的事情能让我在一定程度上做到

String mytext = " hello     there   ";
mytext = mytext.replaceAll("( )+", " ");

但事实并非如此。


当前回答

"[ ]{2,}"

这将匹配多个空格。

String mytext = " hello     there   ";
//without trim -> " hello there"
//with trim -> "hello there"
mytext = mytext.trim().replaceAll("[ ]{2,}", " ");
System.out.println(mytext);

输出:

hello there

其他回答

这对我来说非常有效:sValue = sValue.trim()。replaceAll("\\s+", " ");

检查下这个吗……

public static void main(String[] args) {
    String s = "A B  C   D    E F      G\tH I\rJ\nK\tL";
    System.out.println("Current      : "+s);
    System.out.println("Single Space : "+singleSpace(s));
    System.out.println("Space  count : "+spaceCount(s));
    System.out.format("Replace  all = %s", s.replaceAll("\\s+", ""));

    // Example where it uses the most.
    String s = "My name is yashwanth . M";
    String s2 = "My nameis yashwanth.M";

    System.out.println("Normal  : "+s.equals(s2));
    System.out.println("Replace : "+s.replaceAll("\\s+", "").equals(s2.replaceAll("\\s+", "")));

} 

如果字符串只包含单个空格,则replace()将不替换,

如果空格多于一个,则执行replace()操作并删除空格。

public static String singleSpace(String str){
    return str.replaceAll("  +|   +|\t|\r|\n","");
}

计算字符串中的空格数。

public static String spaceCount(String str){
    int i = 0;
    while(str.indexOf(" ") > -1){
      //str = str.replaceFirst(" ", ""+(i++));
        str = str.replaceFirst(Pattern.quote(" "), ""+(i++)); 
    }
    return str;
}

pattern .quote("?")返回字面模式字符串。

你只需要:

replaceAll("\\s{2,}", " ").trim();

你可以匹配一个或多个空格,用一个空格替换它们,然后在开头和结尾修剪空白(你实际上可以通过先修剪然后匹配来反转正则表达式,就像有人指出的那样)。

要快速测试,请尝试:

System.out.println(new String(" hello     there   ").trim().replaceAll("\\s{2,}", " "));

它会返回:

"hello there"

我知道replaceAll方法更简单,但我也想张贴这个。

public static String removeExtraSpace(String input) {
    input= input.trim();
    ArrayList <String> x= new ArrayList<>(Arrays.asList(input.split("")));
    for(int i=0; i<x.size()-1;i++) {
        if(x.get(i).equals(" ") && x.get(i+1).equals(" ")) { 
            x.remove(i); 
            i--; 
        }
    }
    String word="";
    for(String each: x) 
        word+=each;
    return word;
}

使用Apache commons StringUtils。normalizeSpace(String str)方法。点击这里查看文档