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

" hello     there   "

变成了这样的东西

"hello there"

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

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

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

但事实并非如此。


当前回答

试试这个。

示例代码

String str = " hello     there   ";
System.out.println(str.replaceAll("( +)"," ").trim());

输出

hello there

首先,它将所有空格替换为单个空格。我们必须要做修剪字符串,因为开始的字符串和结束的字符串,它会取代所有的空格,如果字符串有空格在开始的字符串和结束的字符串,所以我们需要修剪它们。然后你会得到你想要的字符串。

其他回答

可以使用字符串标记器

 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());

看到String.replaceAll。

使用正则表达式“\s”并替换为“”。

然后使用String.trim。

我知道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;
}

trim()方法删除开头和结尾的空格,使用regex“\s+”的replaceAll("regex", "string to replace")方法匹配多个空格,并将其替换为单个空格

myText = myText.trim().replaceAll("\\s+"," ");

如果你已经在你的项目中使用了Guava(19+节),你可能想要使用这个:

CharMatcher.whitespace().trimAndCollapseFrom(input, ' ');

或者,如果你需要删除空格符号(或U+0020,查看更多空白),使用:

CharMatcher.anyOf(" ").trimAndCollapseFrom(input, ' ');