Remove white spaces from a string
Java provides several methods for removing whitespace from strings. trim() strips ASCII whitespace from both ends, while strip(), stripLeading(), and stripTrailing() (Java 11+) are Unicode-aware. For removing whitespace from within a string, replaceAll(\
In this article, we are going to look at how to remove white spaces from a string.
Contents
Common ways to remove white spaces from string
Common ways to remove white spaces from string
The easiest way to remove white spaces from a string is to call String.trim()String.trim()'U+0020'
For example, in below sample code we are removing white spaces from s1 = " Hello "s2 = " \0 Hello \r"String.trim()public class RemoveWhiteSpaces {
public static void main(String[] args) {
String s1 = " Hello ";
System.out.println("Length of s1 before removing white spaces : " +(s1.length()));
System.out.println("Length of s1 before after trimming : " +(s1.trim().length()));
String s2 = " \0 Hello \r";
System.out.println("Length of s2 before removing white spaces : " +(s2.length()));
System.out.println("Length of s2 before after trimming : " +(s2.trim().length()));
}
}Length of s1 before removing white spaces : 7
Length of s1 before after trimming : 5
Length of s2 before removing white spaces : 10
Length of s2 before after trimming : 5
To remove white spaces, we can also use String.strip()String.strip()public class RemoveWhiteSpaces {
public static void main(String[] args) {
String s3 = " Hello ";
System.out.println("Length of s3 before removing white spaces : " +(s3.length()));
System.out.println("Length of s3 before after stripping : " +(s3.strip().length()));
String s4 = " \0 Hello \r";
System.out.println("Length of s4 before removing white spaces : " +(s4.length()));
System.out.println("Length of s4 before after stripping : " +(s4.strip().length()));
}
}" \0 Hello \r"Length of s3 before removing white spaces : 7
Length of s3 before after stripping : 5
Length of s4 before removing white spaces : 10
Length of s4 before after stripping : 7
If you want to remove white spaces from the beginning of string you can use String.stripLeading()String.stripTrailing()
Above example complete source code can be found at