Java如何用字符串中的单个空格替换2个或更多空格并删除前导和尾随空格

时间:2010-05-28 20:43:12

标签: java regex string replace

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

" hello     there   "

看起来像这样的东西

"hello there"

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

像这样的东西让我部分地在那里

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

但不完全。

30 个答案:

答案 0 :(得分:402)

试试这个:

String after = before.trim().replaceAll(" +", " ");

另见


trim()正则表达式

也可以只使用一个replaceAll执行此操作,但这比trim()解决方案的可读性低得多。尽管如此,这里提供的只是为了展示正则表达式可以做什么:

    String[] tests = {
        "  x  ",          // [x]
        "  1   2   3  ",  // [1 2 3]
        "",               // []
        "   ",            // []
    };
    for (String test : tests) {
        System.out.format("[%s]%n",
            test.replaceAll("^ +| +$|( )+", "$1")
        );
    }

有3个替代品:

  • ^_+:字符串开头的任何空格序列
    • 匹配并替换$1,捕获空字符串
  • _+$:字符串末尾的任何空格序列
    • 匹配并替换$1,捕获空字符串
  • (_)+:任何与上述任何一个都不匹配的空间序列,意味着它位于中间
    • 匹配并替换为$1,后者捕获单个空格

另见

答案 1 :(得分:134)

你只需要一个:

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

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

要快速测试一下,请尝试:

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

它会返回:

"hello there"

答案 2 :(得分:37)

使用Apache commons StringUtils.normalizeSpace(String str)方法。见docs here

答案 3 :(得分:15)

这对我很有用:sValue = sValue.trim().replaceAll("\\s+", " ");

答案 4 :(得分:13)

要消除String开头和结尾的空格,请使用String#trim()方法。然后使用您的mytext.replaceAll("( )+", " ")

答案 5 :(得分:12)

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

答案 6 :(得分:10)

"[ ]{2,}"

这将匹配多个空格。

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

输出:

hello there

答案 7 :(得分:9)

mytext = mytext.replaceAll("\\s+"," ");

答案 8 :(得分:8)

试试这个。

示例代码

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

<强>输出

hello there

首先,它将用单个空格替换所有空格。我们不得不修剪String,因为String的开始和String的结尾如果String在开始时String有空格,它将用单个空格替换所有空格StringString的结尾所以我们需要修剪它们。比得到你想要的{{1}}。

答案 9 :(得分:6)

String blogName = "how to   do    in  java   .         com"; 
 
String nameWithProperSpacing = blogName.replaceAll("\\\s+", " ");

答案 10 :(得分:3)

你也可以使用外观。

test.replaceAll("^ +| +$|(?<= ) ", "");

test.replaceAll("^ +| +$| (?= )", "")

<space>(?= )匹配空格字符,后跟另一个空格字符。因此,在连续的空格中,它将匹配除了最后一个空格之外的所有空格,因为它后面没有空格字符。这将在删除操作后为连续空格留出一个空格。

示例:

    String[] tests = {
            "  x  ",          // [x]
            "  1   2   3  ",  // [1 2 3]
            "",               // []
            "   ",            // []
        };
        for (String test : tests) {
            System.out.format("[%s]%n",
                test.replaceAll("^ +| +$| (?= )", "")
            );
        }

答案 11 :(得分:3)

修剪()

仅删除领先&amp;尾随空格。

来自Java Doc, “返回一个字符串,其值为此字符串,删除了任何前导和尾随空格。”

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

“D ev Dum 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

答案 12 :(得分:2)

到目前为止,提供了许多正确答案,我看到很多反对意见。但是,上述方法将有效,但不能真正优化或难以理解。 我最近遇到了每个开发人员都会喜欢的解决方案。

String nameWithProperSpacing = StringUtils.normalizeSpace( stringWithLotOfSpaces );

您完成了。 这是可读的解决方案。

答案 13 :(得分:2)

在科特林,它看起来像这样

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

答案 14 :(得分:1)

这对我有用

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

其中filter是跟随函数,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();
}

答案 15 :(得分:1)

String str = " hello world"

首先减少空间

str = str.trim().replaceAll(" +", " ");

大写第一个字母并小写其他所有内容

str = str.substring(0,1).toUpperCase() +str.substring(1,str.length()).toLowerCase();

答案 16 :(得分:1)

您应该这样做

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

在圆括号中放入+。

答案 17 :(得分:1)

流版本,过滤空格和制表符。

Stream.of(str.split("[ \\t]")).filter(s -> s.length() > 0).collect(Collectors.joining(" "))

答案 18 :(得分:0)

以下代码将压缩单词之间的任何空格,并删除字符串开头和结尾的所有空格

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

这将输出a string with many spaces, a tab and a newline

请注意,所有不可打印的字符(包括空格,制表符和换行符)将被压缩或删除


有关更多信息,请参见各自的文档:

答案 19 :(得分:0)

请参阅String.replaceAll

使用正则表达式"\s"并替换为" "

然后使用String.trim

答案 20 :(得分:0)

最简单的删除字符串中空格的方法。

 public String removeWhiteSpaces(String returnString){
    returnString = returnString.trim().replaceAll("^ +| +$|( )+", " ");
    return returnString;
}

答案 21 :(得分:0)

String myText = "   Hello     World   ";
myText = myText.trim().replace(/ +(?= )/g,'');


// Output: "Hello World"

答案 22 :(得分:0)

String str = "  this is string   ";
str = str.replaceAll("\\s+", " ").trim();

答案 23 :(得分:0)

  

可以使用字符串令牌生成器

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

答案 24 :(得分:0)

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

答案 25 :(得分:0)

您好,谢谢您的延迟! 这是您正在寻找的最佳,最高效的答案:

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, " "));
}

因此,此示例的输出将是: 我叫Kingkon。

但是,此方法也会删除字符串可能具有的“ \ n”。因此,如果您不希望这样做,请使用以下简单方法:

while (str.contains("  ")){  //2 spaces
str = str.replace("  ", " "); //(2 spaces, 1 space) 
}

如果您也想去除前导和尾随空格,请添加:

str = str.trim();

答案 26 :(得分:0)

我的方法之前,我发现第二个答案使用正则表达式作为更好的解决方案。也许有人需要这个代码。

private String replaceMultipleSpacesFromString(String s){
    if(s.length() == 0 ) return "";

    int timesSpace = 0;
    String res = "";

    for (int i = 0; i < s.length(); i++) {
        char c = s.charAt(i);

        if(c == ' '){
            timesSpace++;
            if(timesSpace < 2)
                res += c;
        }else{
            res += c;
            timesSpace = 0;
        }
    }

    return res.trim();
}

答案 27 :(得分:0)

检查一下......

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+", "")));

} 

如果String只包含单个空格,则replace()将不会替换,

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

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(&#34;?&#34;)返回文字模式字符串。

答案 28 :(得分:-1)

请使用以下代码

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

答案 29 :(得分:-1)

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函数。