336

Looking for quick, simple way in Java to change this string

" hello     there   "

to something that looks like this

"hello there"

where I replace all those multiple spaces with a single space, except I also want the one or more spaces at the beginning of string to be gone.

Something like this gets me partly there

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

but not quite.

ajb
  • 31,309
  • 3
  • 58
  • 84
Nessa
  • 3,369
  • 2
  • 16
  • 3

32 Answers32

571

Try this:

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

See also


No trim() regex

It's also possible to do this with just one replaceAll, but this is much less readable than the trim() solution. Nonetheless, it's provided here just to show what regex can do:

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

There are 3 alternates:

  • ^_+ : any sequence of spaces at the beginning of the string
    • Match and replace with $1, which captures the empty string
  • _+$ : any sequence of spaces at the end of the string
    • Match and replace with $1, which captures the empty string
  • (_)+ : any sequence of spaces that matches none of the above, meaning it's in the middle
    • Match and replace with $1, which captures a single space

See also

polygenelubricants
  • 376,812
  • 128
  • 561
  • 623
  • 13
    +1, especially as it's worth noting that doing `trim()` and then `replaceAll()` uses less memory than doing it the other way around. Not by much, but if this gets called many many times, it might add up, especially if there's a lot of "trimmable whitespace". (`Trim()` doesn't really get rid of the extra space - it just hides it by moving the start and end values. The underlying `char[]` remains unchanged.) – corsiKa May 28 '10 at 21:02
  • I'm not an expert, but using your description of trim(), if the original string is deleted won't it also delete the trimmed string which is a part of it? – Marichyasana Aug 19 '13 at 07:10
  • 2
    It's only a detail, but I think that `( ) +` or `( ){2,}` should be a (very) little more efficient ;) – sp00m Aug 19 '13 at 08:05
  • 6
    Nice regexp. Note: replacing the space ` ` with `\\s` will replace any group of whitespaces with the desired character. – djmj Aug 23 '13 at 01:48
  • 1
    Note that the ( )+ part will match a single space and replace it with a single space. Perhaps (+) would be better so it only matches if there are multiple spaces and the replacement will make a net change to the string. – Lee Meador Jul 27 '16 at 20:34
  • 3
    As Lee Meador mentioned, ```.trim().replaceAll(" +", " ")``` (with two spaces) is faster than ```.trim().replaceAll(" +", " ")``` (with one space). I ran timing tests on strings that had only single spaces and all double spaces, and it came in substantially faster for both when doing a *lot* of operations (millions or more, depending on environment). – Gary S. Weaver Apr 19 '17 at 14:28
  • Your regex replaces a single space by a single space. That's not good for the performance – Christoph S. Nov 05 '22 at 20:09
178

You just need a:

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

where you match one or more spaces and replace them with a single space and then trim whitespaces at the beginning and end (you could actually invert by first trimming and then matching to make the regex quicker as someone pointed out).

To test this out quickly try:

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

and it will return:

"hello there"
Gili
  • 86,244
  • 97
  • 390
  • 689
sarah.ferguson
  • 3,167
  • 2
  • 23
  • 31
  • Careful, if you think the presence of `\\s` in the regex means that this will reduce sequences of one or more whitespace characters to a single space. It won't always do that. For example, if your original string contains a newline character with a non-whitespace character on either side, it will not replace that newline with a space. This is because `{2,}` requires at least 2 adjacent whitespace characters. – Matt Wallis Apr 13 '23 at 07:03
67

Use the Apache commons StringUtils.normalizeSpace(String str) method. See docs here

fabian
  • 80,457
  • 12
  • 86
  • 114
Monica Granbois
  • 6,632
  • 1
  • 17
  • 17
24

This worked perfectly for me : sValue = sValue.trim().replaceAll("\\s+", " ");

Archimedes Trajano
  • 35,625
  • 19
  • 175
  • 265
Doctor
  • 7,115
  • 4
  • 37
  • 55
24

trim() method removes the leading and trailing spaces and using replaceAll("regex", "string to replace") method with regex "\s+" matches more than one space and will replace it with a single space

myText = myText.trim().replaceAll("\\s+"," ");
k sarath
  • 679
  • 6
  • 8
19

The following code will compact any whitespace between words and remove any at the string's beginning and end

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

This will output a string with many spaces, a tab and a newline

Note that any non-printable characters including spaces, tabs and newlines will be compacted or removed


For more information see the respective documentation:

michael-slx
  • 665
  • 9
  • 15
17
"[ ]{2,}"

This will match more than one space.

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

OUTPUT:

hello there
Gitesh Dalal
  • 178
  • 1
  • 7
15

To eliminate spaces at the beginning and at the end of the String, use String#trim() method. And then use your mytext.replaceAll("( )+", " ").

George
  • 8,368
  • 12
  • 65
  • 106
12

You can first use String.trim(), and then apply the regex replace command on the result.

fabian
  • 80,457
  • 12
  • 86
  • 114
Eyal Schneider
  • 22,166
  • 5
  • 47
  • 78
10

Try this one.

Sample Code

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

OUTPUT

hello there

First it will replace all the spaces with single space. Than we have to supposed to do trim String because Starting of the String and End of the String it will replace the all space with single space if String has spaces at Starting of the String and End of the String So we need to trim them. Than you get your desired String.

Raj Rusia
  • 728
  • 10
  • 15
10
String blogName = "how to   do    in  java   .         com"; 
 
String nameWithProperSpacing = blogName.replaceAll("\\\s+", " ");
Andrzej Sydor
  • 1,373
  • 4
  • 13
  • 28
Narek
  • 101
  • 1
  • 2
6

trim()

Removes only the leading & trailing spaces.

From Java Doc, "Returns a string whose value is this string, with any leading and trailing whitespace removed."

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

"D ev Dum my"

replace(), replaceAll()

Replaces all the empty strings in the word,

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

Output:

"DevDummy"

"DevDummy"

"DevDummy"

Note: "\s+" is the regular expression similar to the empty space character.

Reference : https://www.codedjava.com/2018/06/replace-all-spaces-in-string-trim.html

Community
  • 1
  • 1
Sameera Nelson
  • 161
  • 1
  • 11
  • What if you only want to replace the places where you have more than one space, but let alone single spaces? – David Jan 03 '23 at 08:54
6

In Kotlin it would look like this

val input = "\n\n\n  a     string with     many    spaces,    \n"
val cleanedInput = input.trim().replace(Regex("(\\s)+"), " ")
Rafael
  • 6,091
  • 5
  • 54
  • 79
5

A lot of correct answers been provided so far and I see lot of upvotes. However, the mentioned ways will work but not really optimized or not really readable. I recently came across the solution which every developer will like.

String nameWithProperSpacing = StringUtils.normalizeSpace( stringWithLotOfSpaces );

You are done. This is readable solution.

Kunal Vohra
  • 2,703
  • 2
  • 15
  • 33
4

You could use lookarounds also.

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

OR

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

<space>(?= ) matches a space character which is followed by another space character. So in consecutive spaces, it would match all the spaces except the last because it isn't followed by a space character. This leaving you a single space for consecutive spaces after the removal operation.

Example:

    String[] tests = {
            "  x  ",          // [x]
            "  1   2   3  ",  // [1 2 3]
            "",               // []
            "   ",            // []
        };
        for (String test : tests) {
            System.out.format("[%s]%n",
                test.replaceAll("^ +| +$| (?= )", "")
            );
        }
Avinash Raj
  • 172,303
  • 28
  • 230
  • 274
2
String str = " hello world"

reduce spaces first

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

capitalize the first letter and lowercase everything else

str = str.substring(0,1).toUpperCase() +str.substring(1,str.length()).toLowerCase();
KhaledMohamedP
  • 5,000
  • 3
  • 28
  • 26
2

See String.replaceAll.

Use the regex "\s" and replace with " ".

Then use String.trim.

Bernhard Barker
  • 54,589
  • 14
  • 104
  • 138
Zak
  • 24,947
  • 11
  • 38
  • 68
2

you should do it like this

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

put + inside round brackets.

2
String str = "  this is string   ";
str = str.replaceAll("\\s+", " ").trim();
Ajinkya_M
  • 71
  • 1
  • 1
1

This worked for me

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

where filter is following function and scan is the input string:

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();
}
Radiodef
  • 37,180
  • 14
  • 90
  • 125
Mr_Hmp
  • 2,474
  • 2
  • 35
  • 53
1

The simplest method for removing white space anywhere in the string.

 public String removeWhiteSpaces(String returnString){
    returnString = returnString.trim().replaceAll("^ +| +$|( )+", " ");
    return returnString;
}
Sandun Susantha
  • 1,010
  • 1
  • 10
  • 11
0

check this...

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

} 

If String contains only single-space then replace() will not-replace,

If spaces are more than one, Then replace() action performs and removes spacess.

public static String singleSpace(String str){
    return str.replaceAll("  +|   +|\t|\r|\n","");
}

To count the number of spaces in a String.

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("?") returns literal pattern String.

Yash
  • 9,250
  • 2
  • 69
  • 74
0

My method before I found the second answer using regex as a better solution. Maybe someone needs this code.

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();
}
trinity420
  • 670
  • 7
  • 19
0

Stream version, filters spaces and tabs.

Stream.of(str.split("[ \\t]")).filter(s -> s.length() > 0).collect(Collectors.joining(" "))
Aris2World
  • 1,214
  • 12
  • 22
0

I know replaceAll method is much easier but I wanted to post this as well.

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;
}
esranur
  • 11
0
String myText = "   Hello     World   ";
myText = myText.trim().replace(/ +(?= )/g,'');


// Output: "Hello World"
alaswer
  • 135
  • 9
0

string.replaceAll("\s+", " ");

Amod Kunwar
  • 61
  • 1
  • 1
0

If you already use Guava (v. 19+) in your project you may want to use this:

CharMatcher.whitespace().trimAndCollapseFrom(input, ' ');

or, if you need to remove exactly SPACE symbol ( or U+0020, see more whitespaces) use:

CharMatcher.anyOf(" ").trimAndCollapseFrom(input, ' ');
æ-ra-code
  • 2,140
  • 30
  • 28
-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;
        }
    }
}

The above solution is the algorithm with the complexity of O(n) without using any java function.

LMeyer
  • 2,570
  • 1
  • 24
  • 35
-1

Please use below code

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());
    }
}
v.ladynev
  • 19,275
  • 8
  • 46
  • 67
Piyush
  • 5,607
  • 4
  • 27
  • 27
-1

Hello sorry for the delay! Here is the best and the most efficiency answer that you are looking for:

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

So your output of this example will be: My name is kingkon.

However this method will remove also the "\n" that your string may has. So if you do not want that just use this simple method:

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

And if you want to strip the leading and trailing spaces too just add:

str = str.trim();
-1

String Tokenizer can be used

 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());
Swaran
  • 1