By Nessa

2010-05-28 20:43:11 8 Comments

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.


@k sarath 2020-05-16 15:51:36

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

@Nick 2020-06-12 07:30:21

Code-only answers are discouraged. Please click on edit and add some words summarising how your code addresses the question, or perhaps explain how your answer differs from the previous answers. Thanks

@Sandun Susantha 2020-06-12 06:51:33

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

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

@michael-slx 2019-04-03 12:06:38

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

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:

@alaswer 2020-01-03 00:11:59

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

// Output: "Hello World"

@Ajinkya_M 2019-11-28 09:04:46

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

@Swaran 2019-10-31 10:14:00

String Tokenizer can be used

 String str = "  hello    there  ";
            StringTokenizer stknzr = new StringTokenizer(str, " ");
            StringBuffer sb = new StringBuffer();
                sb.append(stknzr.nextElement()).append(" ");

@Rafael 2019-10-21 10:30:49

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

@Kunal Vohra 2019-10-07 07:33:20

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.

@esranur 2019-06-09 04:29:34

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(" ")) { 
    String word="";
    for(String each: x) 
    return word;

@platzhersh 2019-10-16 07:37:14

Even though this works, it is far from the easiest solution.

@kostas poimenidhs 2019-01-29 22:18:28

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

@Gitesh Dalal 2017-12-15 15:58:24

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


hello there

@Aris2World 2018-11-26 16:48:19

Stream version, filters spaces and tabs.

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

@kiro malak 2018-11-26 16:21:17

you should do it like this

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

put + inside round brackets.

@Sameera 2018-06-02 17:35:48


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





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

Reference :

@Mr_Hmp 2013-11-24 06:27:20

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


    return sb.toString();

@Lee Meador 2016-07-27 20:30:27

This would replace <space><tab> with a space but not <tab><tab>. That's a minor problem, seems like.

@Raj S. Rusia 2017-03-28 08:56:14

Try this one.

Sample Code

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


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.

@Doctor 2015-11-10 11:20:04

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

@Doctor 2017-02-10 02:04:43

People edited my answer. The original was: sValue = sValue.replaceAll("\s+", "").trim();

@Jose Rui Santos 2018-10-03 08:36:34

Was edited because your original answer removes all the spaces and that's not what the OP asked

@sarah.ferguson 2013-12-09 13:31:52

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"

@juanmeza 2015-08-14 04:27:12

this worked for me, since my string also had new lines with white spaces

@Michael 2015-11-10 11:39:05

I'd probably trim first because then you're saving the regex a bit of work.

@mwarren 2016-02-01 13:54:03

@sarah.ferguson Please remove the final bracket ")" that shouldn't be there in the first replaceAll. Thanks. - The system wouldn't let me do it! (Nothing less than 6 chars is eligible for an edit..)

@Lee Meador 2016-07-27 20:29:09

Note that this does replace one space with another space in the case where there are not multiple spaces together. There is no need to do the replacement in that case though you might want it since you are replacing one tab with a single space too. It would be nice to only recognize multiple spaces only.

@Gili 2016-09-02 03:11:10

@LeeMeador Fixed by replacing + with {2,}.

@geowar 2017-02-04 21:56:46

This will NOT replace a single tab with a space. FAIL.

@sarah.ferguson 2017-02-15 16:44:41

@geowar where did the question ask for tabs sorry? I'm sure the above doesn't replace ☮ symbols as well for that matter.. and neither ✌...

@geowar 2017-02-18 18:11:50

Ah! my bad! un-downvote… Thanks for the catchSarah.ferguson.

@user1870400 2017-12-13 10:15:57

wait a second @geowar This does replace a single table with a space. I just tried it

@trinity420 2016-02-13 11:52:35

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 == ' '){
            if(timesSpace < 2)
                res += c;
            res += c;
            timesSpace = 0;

    return res.trim();

@Laur Ivan 2016-03-07 14:24:40

Interesting, but white space means more than just blanks.

@trinity420 2016-03-07 21:53:59

@LaurIvan what do you mean?

@Laur Ivan 2016-03-08 14:51:55

this entry has a good explanation on what \s stands for in regular expressions (space, tab, new line, form feed).

@trinity420 2016-03-08 19:06:40

@LaurIvan Your link is broken but you are right. This problem could be solved by iterating through the input string, removing every non-alphabetic, non-numeric and non-space character, I think.

@Piyush 2015-10-27 07:07:51

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

            sb.append(st.nextElement()).append(" ");


@Yash 2015-10-28 06:31:08

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.

@Monica Granbois 2015-08-01 23:21:43

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

@Somaiah Kumbera 2019-04-09 16:50:05

Good idea, but this removes newlines among other things

@Eyal Schneider 2010-05-28 20:46:28

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

@vuhung3990 2015-10-30 06:42:55

trim() will remove all space at begin and end of string, it's not apply for space between words

@devmohd 2015-05-27 15:35:20

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 {
            prev = cur;

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

@Avinash Raj 2015-03-06 18:48:48

You could use lookarounds also.

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


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.


    String[] tests = {
            "  x  ",          // [x]
            "  1   2   3  ",  // [1 2 3]
            "",               // []
            "   ",            // []
        for (String test : tests) {
                test.replaceAll("^ +| +$| (?= )", "")

@Lee Meador 2016-07-27 20:26:38

The way you have it, it will match any space(s) on the front or the end or any single space with another space after it. That means "a....b" will match 3 times and replace three times. It iterates over all the internal spaces inside the replaceAll() method. Perhaps you could change it to match any sequence of 2 or more spaces all at once and reduce the internal iteration.

@Lee Meador 2016-07-27 20:32:31

Maybe <space>+(?=<space>) would do it.

@KhaledMohamedP 2013-12-15 20:34:14

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

@Zak 2010-05-28 20:48:39

See String.replaceAll.

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

Then use String.trim.

@sarah.ferguson 2013-12-09 13:27:09

new String(" hello there ").replaceAll("\\s", "+") returns a +hello+++++++there+++ so definitely doesn't work..

@manish_s 2014-02-14 08:34:17

Try new String(" hello there ").trim().replaceAll("\\s+", " ")

@polygenelubricants 2010-05-28 20:49:51

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

@corsiKa 2010-05-28 21:02:22

+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.)

@Marichyasana 2013-08-19 07:10:57

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?

@sp00m 2013-08-19 08:05:45

It's only a detail, but I think that ( ) + or ( ){2,} should be a (very) little more efficient ;)

@djmj 2013-08-23 01:48:32

Nice regexp. Note: replacing the space ` ` with \\s will replace any group of whitespaces with the desired character.

@Lee Meador 2016-07-27 20:34:39

Note that the ( )+ part will match a single space and replace it with a single space. Perhaps (<space><space>+) would be better so it only matches if there are multiple spaces and the replacement will make a net change to the string.

@Gary S. Weaver 2017-04-19 14:28:37

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

@folone 2010-05-28 20:49:01

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

Related Questions

Sponsored Content

67 Answered Questions

[SOLVED] How to replace all occurrences of a string?

44 Answered Questions

[SOLVED] How do I convert a String to an int in Java?

32 Answered Questions

[SOLVED] How do I create a Java string from the contents of a file?

35 Answered Questions

[SOLVED] How to split a string in Java

  • 2010-08-14 03:01:53
  • riyana
  • 3937762 View
  • 1659 Score
  • 35 Answer
  • Tags:   java string split

42 Answered Questions

[SOLVED] How to generate a random alpha-numeric string?

59 Answered Questions

[SOLVED] How do I read / convert an InputStream into a String in Java?

27 Answered Questions

[SOLVED] How to get an enum value from a string value in Java?

  • 2009-03-02 22:56:34
  • Malachi
  • 1150239 View
  • 2008 Score
  • 27 Answer
  • Tags:   java enums

39 Answered Questions

[SOLVED] How to check if a String is numeric in Java

  • 2009-07-09 09:49:47
  • Craig Angus
  • 1460767 View
  • 896 Score
  • 39 Answer
  • Tags:   java string numeric

6 Answered Questions

[SOLVED] Strip Leading and Trailing Spaces From Java String

  • 2011-07-11 15:37:59
  • Tyler DeWitt
  • 420090 View
  • 278 Score
  • 6 Answer
  • Tags:   java string replace

35 Answered Questions

Sponsored Content