Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove all white spaces in java [duplicate]

People also ask

How do you remove all white spaces in Java?

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

How do you trim white spaces in a string in Java?

The trim() method in Java String is a built-in function that eliminates leading and trailing spaces. The Unicode value of space character is '\u0020'. The trim() method in java checks this Unicode value before and after the string, if it exists then removes the spaces and returns the omitted string.

How do you remove spaces from a loop in Java?

replaceAll("\\s","") removes all whitespaces. Also you can remove other non visible symbols, such as \tab etc.


java.lang.String class has method substring not substr , thats the error in your program.

Moreover you can do this in one single line if you are ok in using regular expression.

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

Why not use a regex for this?

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

In the context of a regex, \s will remove anything that is a space character (including space, tab characters etc). You need to escape the backslash in Java so the regex turns into \\s. Also, since Strings are immutable it is important that you assign the return value of the regex to a.


The most intuitive way of doing this without using literals or regular expressions:

yourString.replaceAll(" ","");

Replace all the spaces in the String with empty character.

String lineWithoutSpaces = line.replaceAll("\\s+","");