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

" hello     there   "

变成了这样的东西

"hello there"

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

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

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

但事实并非如此。


当前回答

在Kotlin中是这样的

val input = "\n\n\n  a     string with     many    spaces,    \n"
val cleanedInput = input.trim().replace(Regex("(\\s)+"), " ")

其他回答

试试这个。

示例代码

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

输出

hello there

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

这对我很有效

scan= filter(scan, " [\\s]+", " ");
scan= sac.trim();

其中filter跟在function后面,scan是输入字符串:

public String filter(String scan, String regex, String replace) {
    StringBuffer sb = new StringBuffer();

    Pattern pt = Pattern.compile(regex);
    Matcher m = pt.matcher(scan);

    while (m.find()) {
        m.appendReplacement(sb, replace);
    }

    m.appendTail(sb);

    return sb.toString();
}

削减()

只删除开头和结尾空格。

从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

你好,抱歉耽搁了! 以下是你正在寻找的最佳和最有效的答案:

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

看到String.replaceAll。

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

然后使用String.trim。