How to remove all white spaces from a String in Java

Problem

Given a String with white spaces, the task is to remove all white spaces from a string.

Example

Input:

"   This is an example    "

Output: Thisisanexample

Solution

We can solve this problem in the following ways:

  • Using a for loop.
  • Using the replaceAll() method.

Using a for loop

Approach

  • Convert string to a character array.
  • Declare a temporary string.
  • Traverse the character array.
    • Check if the present character is white space or not.
    • If it is not white space, then add it to a temporary string.
  • Copy temporary string to original string.
  • Print the string.
class Solution {
public static void main( String args[] ) {
//given string
String str = " This is an example ";
//convert string to character array
char[] arr = str.toCharArray();
//take temporary string
String tempStr = "";
//traverse all the characters
for(char c:arr){
//if present character is not a white space then add to it temporary string
if(c != ' '){
tempStr += c;
}
}
//assign tempStr to str
str = tempStr;
//print string
System.out.println(str);
}
}

Using the replaceAll() method

Approach

  • We will use the in-built method replaceAll() to solve this.
  • The method replaceAll() will take two parameters:
    • Param 1: Provide the string that needs to be replaced.
    • Param 2: Provide the new string that will be placed in the place of Param 1.
  • This method returns the modified string.
  • Pass the returned string to the original string.
  • Print the string.
class HelloWorld {
public static void main( String args[] ) {
//given string
String str = " This is an example ";
//replacing the white spaces
str = str.replaceAll(" ","");
//print modified string
System.out.println(str);
}
}