How to remove whitespaces from a string in Java
In this shot, we will discuss how to remove all whitespaces from a string in Java. Here, we will take a string from the user as input and then we will remove all the spaces from it.
Solution approach
We have two methods to remove all the whitespaces from the string.
-
In Java, we can use the built-in
replaceAll()method to remove all the whitespaces of the given string. In fact, we can replace any character of a string with another using this method. -
We can also remove whitespaces manually. To remove all the whitespaces, we have to traverse through the string once and append the characters other than whitespaces in a string buffer. Then, we convert that
StringBufferinto a string using the built-in Java methodtoString().
Code
To understand this better let’s look at the below code snippet.
Input any text with whitespaces. For example:
Educative is cool!
import java.util.Scanner;class RemoveWhitespaces {public static void main(String[] args) {Scanner sc= new Scanner((System.in));System.out.println("Enter the input String:-");String input= sc.nextLine();String ans1= input.replaceAll("\\s","");//replace all whitespaces with blankString ans2=removeSpaces(input);System.out.println("Desired string using method-1:\t"+ans1);System.out.println("Desired string using method-2:\t"+ans2);}static String removeSpaces(String str){StringBuffer st= new StringBuffer();for(char c:str.toCharArray()){if(c!=' ' && c!='\t'){st.append(c);}}return st.toString();}}
Enter the input below
Explanation
-
In line 1, we imported the
java.util.Scannerclass to read input from the user. -
In line 7, inside the main function, we took the input string from the user by creating a
Scannerobject and stored that input in aStringinput. -
In line 8, we call the
replaceAll()function, replace all the whitespaces with blank, and store the resultant string in theans1variable. -
In line 9, we call the
removeSpaces()method and pass the input string as a parameter to it. This method will return the string without whitespaces and store the resultant string in a variableans2. -
In lines 10 and 11, we print the output that we get by using
method-1andmethod-2respectively to compare them. -
In lines 13 to 21, we defined the
removeSpaces()function. Inside the function, we initialized a variablestofStringBuffertype and we run aforloop for the given string. If any character other than white space is found then append it tost. -
After ending the loop, we convert
StringBufferinto a string using thetoString()method and return it. -
At the input/output section we can see we get the same output for both the methods.
In these ways, we can remove all whitespaces from a string in Java.