Learnitweb

Remove white spaces from String in Java

Remove white spaces from string using build-in methods

Approach: We’ll use replaceAll() method of String class and replace all white spaces with “”.

import java.util.Scanner;

public class RemoveWhiteSpacesExample {

	public static void main(String[] args) {
	      Scanner sc = new Scanner(System.in);
        System.out.println("Enter input string:");
        
        //Read input string from console
        String inputString = sc.nextLine();
        
        //Replace white space using input string using replaceAll method
        String stringWithoutSpaces = inputString.replaceAll("\\s+", "");
        
        System.out.println("Input string : "+inputString);
        System.out.println("Input string without Spaces : "+stringWithoutSpaces);
        sc.close();
	}
}

Output

Enter input string:
 Java white space removal example using replaceAll() method
 Input string : Java white space removal example using replaceAll() method
 Input string without Spaces : JavawhitespaceremovalexampleusingreplaceAll()method

Note: We could have used “\s+” instead of “\s”. Both produce the same result with almost same performance. But, when the number of consecutive spaces increase, “\s+” is faster than “\s”.

Remove white spaces from string without using build-in method

Approach:

  • Convert String to character Array.
  • Iterate array and match each element of array with white space.
  • Create a blank String(in our case StringBuffer for performance reasons)
  • If element is not matched(to white space) then append the character to the result.
import java.util.Scanner;

public class RemoveWhiteSpacesExample {

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
        System.out.println("Enter input string:");
        
        //Read input string from console
        String inputString = sc.nextLine();
        
        //Convert string to character array
        char[] charArray = inputString.toCharArray();
        
        /* Using StringBuffer for string manipulation for performance reasons
        Later we'll change StringBuffer to String */
        StringBuffer stringWithoutSpaces = new StringBuffer("");
         
        for (int i = 0; i < charArray.length; i++) {
            if ( (charArray[i] != ' ') && (charArray[i] != '\t') ){
                stringWithoutSpaces = stringWithoutSpaces.append(charArray[i]) ;
            }
        }
        
        System.out.println("Input String : "+inputString);
        System.out.println("Input String Without Spaces : "+stringWithoutSpaces.toString());
        sc.close();
	}
}

Output

Enter input string:
Java white space removal example using replaceAll() method
Input String : Java white space removal example using replaceAll() method
Input String Without Spaces : JavawhitespaceremovalexampleusingreplaceAll()method