简体   繁体   中英

How to remove spaces in between the String

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

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

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

You can use replaceAll which 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:

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

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

首先去掉多个空格:

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

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,

        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

Eg. to remove space between words in a string:

String example = "Interactive Resource";

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

Output: Without space string: InteractiveResource

如果你想打印一个没有空格的字符串,只需将参数 sep='' 添加到打印函数中,因为该参数的默认值为“”。

//user this for removing all the whitespaces from a given string for example a =" 1 2 3 4"
//output: 1234 
a.replaceAll("\\s", "")

String s2=" 1 2 3 4 5 "; String after=s2.replace(" ", "");

this work for me

String string_a = "AAAA           BBB";
String actualTooltip_3 = string_a.replaceAll("\\s{2,}"," ");
System.out.println(String actualTooltip_3);

/// OUTPUT will be:AAA BBB//

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM