In this article, we are going to look at how to remove white spaces from a string.

Contents

The easiest way to remove white spaces from a string is to call String.trim() method. Note that String.trim() will remove any character whose unicode value is less than or equal to 'U+0020' (the space character).

For example, in below sample code we are removing white spaces from s1 = " Hello " and s2 = " \0 Hello \r", you can see that String.trim() method will remove control characters as well. 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())); } } When you run the above code snippet, it will produce the below output. 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() method. Note that String.strip() method is unicode aware function, so it will not remove control characters. 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())); } } When you run the above code snippet, it will produce the below output. As you can see from second string " \0 Hello \r" it did not remove control characters. 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() and to remove trailing spaces you can use String.stripTrailing()

Above example complete source code can be found at Github