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

" hello     there   "

变成了这样的东西

"hello there"

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

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

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

但事实并非如此。


当前回答

public class RemoveExtraSpacesEfficient {

    public static void main(String[] args) {

        String s = "my    name is    mr    space ";

        char[] charArray = s.toCharArray();

        char prev = s.charAt(0);

        for (int i = 0; i < charArray.length; i++) {
            char cur = charArray[i];
            if (cur == ' ' && prev == ' ') {

            } else {
                System.out.print(cur);
            }
            prev = cur;
        }
    }
}

上面的解决方案是复杂度为O(n)的算法,没有使用任何java函数。

其他回答

您可以首先使用String.trim(),然后对结果应用regex replace命令。

"[ ]{2,}"

这将匹配多个空格。

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

输出:

hello there

下面的代码将压缩单词之间的空白,并删除字符串开头和结尾的空白

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 blogName = "how to   do    in  java   .         com"; 
 
String nameWithProperSpacing = blogName.replaceAll("\\\s+", " ");

削减()

只删除开头和结尾空格。

从Java文档, 返回值为此字符串的字符串,删除前导和尾部的任何空格。

System.out.println(" D ev  Dum my ".trim());

“D ev House my”

replace(), replaceAll()

替换单词中的所有空字符串,

System.out.println(" D ev  Dum my ".replace(" ",""));

System.out.println(" D ev  Dum my ".replaceAll(" ",""));

System.out.println(" D ev  Dum my ".replaceAll("\\s+",""));

输出:

"DevDummy"

"DevDummy"

"DevDummy"

注意:“\s+”为类似空格字符的正则表达式。

参考资料:https://www.codedjava.com/2018/06/replace-all-spaces-in-string-trim.html