Java 如何删除字符串之间的空格

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18870395/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 11:47:19  来源:igfitidea点击:

How to remove spaces in between the String

javaregexstring

提问by Lav patel

I have below String

我有以下字符串

  string = "Book Your Domain And Get\n \n\n \n \n \n Online Today."
  string = str.replace("\s","").trim();

which returning

哪个返回

  str = "Book Your Domain And Get     Online Today."

But what is want is

但想要的是

  str = "Book Your Domain And Get Online Today."

I have tried Many Regular Expression and also googled but got no luck. and did't find related question, Please Help, Many Thanks in Advance

我尝试了许多正则表达式,也用谷歌搜索但没有运气。并没有找到相关问题,请帮忙,非常感谢提前

采纳答案by Rafi Kamal

Use \\s+instead of \\sas there are two or more consecutive whitespaces in your input.

使用\\s+而不是\\s因为您的输入中有两个或多个连续的空格。

string = str.replaceAll("\s+"," ")

回答by Rohit Jain

You can use replaceAllwhich takes a regex as parameter. And it seems like you want to replace multiple spaces with a single space. You can do it like this:

您可以使用replaceAllwhich 将正则表达式作为参数。似乎您想用一个空格替换多个空格。你可以这样做:

string = str.replaceAll("\s{2,}"," ");

It will replace 2 or more consecutive whitespaces with a single whitespace.

它将用一个空格替换 2 个或多个连续的空格。

回答by Rohit Jain

First get rid of multiple spaces:

首先去掉多个空格:

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

回答by ?mer

If you want to just remove the white space between 2 words or characters and not at the end of string then here is the regex that i have used,

如果您只想删除 2 个单词或字符之间的空格而不是字符串末尾的空格,那么这里是我使用的正则表达式,

        String s = "   N    OR  15  2    ";

    Pattern pattern = Pattern.compile("[a-zA-Z0-9]\s+[a-zA-Z0-9]", Pattern.CASE_INSENSITIVE); 

    Matcher m = pattern.matcher(s);

        while(m.find()){
        String replacestr = "";


        int i = m.start();
            while(i<m.end()){
                replacestr = replacestr + s.charAt(i);
                i++;
            }

            m = pattern.matcher(s);
        }

        System.out.println(s);

it will only remove the space between characters or words not spaces at the ends and the output is

它只会删除字符或单词之间的空格而不是末尾的空格,输出为

NOR152

NOR152

回答by shahchiragh

Eg. to remove space between words in a string:

例如。删除字符串中单词之间的空格:

String example = "Interactive Resource";

String example = "Interactive Resource";

System.out.println("Without space string: "+ example.replaceAll("\\s",""));

System.out.println("Without space string: "+ example.replaceAll("\\s",""));

Output: Without space string: InteractiveResource

输出: Without space string: InteractiveResource