Home » Java » Removing whitespace from strings in Java

Removing whitespace from strings in Java

Posted by: admin November 2, 2017 Leave a comment

Questions:

I have a string like this:

mysz = "name=john age=13 year=2001";

I want to remove the whitespaces in the string. I tried trim() but this removes only whitespaces before and after the whole string. I also tried replaceAll("\\W", "") but then the = also gets removed.

How can I achieve a string with:

mysz2 = "name=johnage=13year=2001"
Answers:

st.replaceAll("\\s+","") removes all whitespaces and non-visible characters (e.g., tab, \n).


st.replaceAll("\\s+","") and st.replaceAll("\\s","") produce the same result.

The second regex is 20% faster than the first one, but as the number consecutive spaces increases, the first one performs better than the second one.


Assign the value to a variable, if not used directly:

st = st.replaceAll("\s+","")

Questions:
Answers:
replaceAll("\s","")

\w = Anything that is a word character

\W = Anything that isn’t a word character (including punctuation etc)

\s = Anything that is a space character (including space, tab characters etc)

\S = Anything that isn’t a space character (including both letters and numbers, as well as punctuation etc)

(Edit: As pointed out, you need to escape the backslash if you want \s to reach the regex engine, resulting in \\s.)

Questions:
Answers:

The most correct answer to the question is:

String mysz2 = mysz.replaceAll("\s","");

I just adapted this code from the other answers. I’m posting it because besides being exactly what the question requested, it also demonstrates that the result is returned as a new string, the original string is not modified as some of the answers sort of imply.

(Experienced Java developers might say “of course, you can’t actually modify a String”, but the target audience for this question may well not know this.)

Questions:
Answers:

How about replaceAll("\\s", ""). Refer here.

Questions:
Answers:

If you prefer utility classes to regexes, there is a method trimAllWhitespace(String) in StringUtils in the Spring Framework.

Questions:
Answers:

You’ve already got the correct answer from Gursel Koca but I believe that there’s a good chance that this is not what you really want to do. How about parsing the key-values instead?

import java.util.Enumeration;
import java.util.Hashtable;

class SplitIt {
  public static void main(String args[])  {

    String person = "name=john age=13 year=2001";

    for (String p : person.split("\s")) {
      String[] keyValue = p.split("=");
      System.out.println(keyValue[0] + " = " + keyValue[1]);
    }
  }
}

output:
name = john
age = 13
year = 2001

Questions:
Answers:

One way to handle String manipulations is StringUtils from Apache commons.

String withoutWhitespace = StringUtils.deleteWhitespace(whitespaces);

You can find it here.
commons-lang includes lots more and is well supported.

Questions:
Answers:

You should use

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

instead of:

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

This way, it will work with more than one spaces between each string.
The + sign in the above regex means “one or more \s”

Questions:
Answers:

If you need to remove unbreakable spaces too, you can upgrade your code like this :

st.replaceAll("[\s|\u00A0]+", "");

Questions:
Answers:

You can do it so simply by

String newMysz = mysz.replace(" ","");

Questions:
Answers:
public static void main(String[] args) {        
    String s = "name=john age=13 year=2001";
    String t = s.replaceAll(" ", "");
    System.out.println("s: " + s + ", t: " + t);
}

Output:
s: name=john age=13 year=2001, t: name=johnage=13year=2001

Questions:
Answers:
String a="string with                multi spaces ";
//or this 
String b= a.replaceAll("\s+"," ");
String c= a.replace("    "," ").replace("   "," ").replace("  "," ").replace("   "," ").replace("  "," ");

//it work fine with any spaces
*don’t forget space in sting b

Questions:
Answers:

The easiest way to do this is by using the org.apache.commons.lang3.StringUtils class of commons-lang3 library such as “commons-lang3-3.1.jar” for example.

Use the static method “StringUtils.deleteWhitespace(String str)” on your input string & it will return you a string after removing all the white spaces from it. I tried your example string “name=john age=13 year=2001” & it returned me exactly the string that you wanted – “name=johnage=13year=2001“. Hope this helps.

Questions:
Answers:

\W means “non word character”. The pattern for whitespace characters is \s. This is well documented in the Pattern javadoc.

Questions:
Answers:

In java we can do following operation:

String pattern="[\s]";
String replace="";
part="name=john age=13 year=2001";
Pattern p=Pattern.compile(pattern);
Matcher m=p.matcher(part);
part=m.replaceAll(replace);
System.out.println(part);

for this you need to import following packages to your program:

import java.util.regex.Matcher;
import java.util.regex.Pattern;

i hope it will help you.

Questions:
Answers:

there are many ways to solve this problem.
you can use split function or replace function of Strings.

for more info refer smilliar problem http://techno-terminal.blogspot.in/2015/10/how-to-remove-spaces-from-given-string.html

Questions:
Answers:

Using Pattern And Matcher it is more Dynamic.

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class RemovingSpace {

    /**
     * @param args
     * Removing Space Using Matcher
     */
    public static void main(String[] args) {
        String str= "jld fdkjg jfdg ";
        String pattern="[\s]";
        String replace="";

        Pattern p= Pattern.compile(pattern);
        Matcher m=p.matcher(str);

        str=m.replaceAll(replace);
        System.out.println(str);    
    }
}

Questions:
Answers:
import java.util.*;
public class RemoveSpace {
    public static void main(String[] args) {
        String mysz = "name=john age=13 year=2001";
        Scanner scan = new Scanner(mysz);

        String result = "";
        while(scan.hasNext()) {
            result += scan.next();
        }
        System.out.println(result);
    }
}

Questions:
Answers:
mysz = mysz.replace(" ","");

First with space, second without space.

Then it is done.

Questions:
Answers:
var str ="hello    the dog is big"
var expression = /\s+/g;
var x =str.replace(expression, "");

return x;

This works for me and locates ll white spaces, not just spaces of a certain size.

Questions:
Answers:

To remove spaces in your example, this is another way to do it:

String mysz = "name=john age=13 year=2001";
String[] test = mysz.split(" ");
mysz = String.join("", mysz);

What this does is it converts it into an array with the spaces being the separators, and then it combines the items in the array together without the spaces.

It works pretty well and is easy to understand.

Questions:
Answers:

You can achieve this without using replaceAll() or any Predefined Method in Java.
this way is preferred:-

public class RemoveSpacesFromString {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        String newString;
        String str = "prashant is good" ;
        int i;
        char[] strArray = str.toCharArray();
        StringBuffer sb =  new StringBuffer();

        for(i = 0; i<strArray.length; i++)
        {
            if(strArray[i]!= ' ' && strArray[i]!= '\t')
            {
                sb.append(strArray[i]);
            }
        }
        System.out.println(sb);

        /*newString = str.replaceAll(" " , "");
        System.out.println(newString);*/
    }
}

Questions:
Answers:

Use apache string util class is better to avoid NullPointerException

org.apache.commons.lang3.StringUtils.replace("abc def ", " ", "")

Output will be:

abcdef

Questions:
Answers:

TRY THIS

    String str="name=john age=13 year=2001";
    String s[]=str.split(" ");
    StringBuilder v=new StringBuilder();
    for (String string : s) {

        v.append(string);
    }
      str=v.toString();

Questions:
Answers:

Use mysz.replaceAll("\\s+","");

Questions:
Answers:

The code you want is

str.replaceAll("\s","");

This will remove all the white spaces.