Java Program To Remove All Whitespaces from a String

Write a Java program to remove all whitespaces from a string with an example. In Java, we can use the string replaceAll method to replace the blank spaces in a string. For this, we have to use the replaceAll(“\s”, “”) where “\s” represents the single space.

package NumPrograms;

import java.util.Scanner;

public class StringRemoveWhiteSp1 {
	
	private static Scanner sc;
	
	public static void main(String[] args) {
		
		sc= new Scanner(System.in);

		System.out.print("Enter String to Remoe White Spaces =  ");
		String str1 = sc.nextLine();
		
		System.out.println("Original String = " + str1);
		
		String str2 = str1.replaceAll("\\s", "");
		System.out.println("Final String = " + str2);
	}
}
Java Program To Remove All Whitespaces from a String

This Java program uses the StringBuffer and for loop to remove all the whitespaces or blank spaces from a string. First, we converted the given string to character array. Next, for(int i =0; i < strArray.length; i++) iterate the string characters, and the if statement if(strArray[i] != ‘ ‘ && strArray[i] != ‘\t’) filters the non-empty characters. Then, append those non-empty characters to a Java string buffer.

package NumPrograms;

import java.util.Scanner;

public class StringRemoveWhiteSp2 {
	private static Scanner sc;
	public static void main(String[] args) {
		
		sc= new Scanner(System.in);
		StringBuffer strBuffer = new StringBuffer();

		System.out.print("Enter String to Remoe White Spaces =  ");
		String str1 = sc.nextLine();
		
		System.out.println("Original String = " + str1);
		
		char[] strArray = str1.toCharArray();
		for(int i =0; i < strArray.length; i++)
		{
			if(strArray[i] != ' ' && strArray[i] != '\t')
			{
				strBuffer.append(strArray[i]);
			}
		}
		
		System.out.println("Final String = " + strBuffer.toString());
	}
}
Enter String to Remoe White Spaces =  learn java programs for free
Original String = learn java programs for free
Final String = learnjavaprogramsforfree

Java program to remove all whitespaces from a string using a while loop.

package NumPrograms;

import java.util.Scanner;

public class StringRemoveWhiteSp3 {
	private static Scanner sc;
	public static void main(String[] args) {
		
		sc= new Scanner(System.in);
		StringBuffer strBuffer = new StringBuffer();

		System.out.print("Enter String to Remove White Spaces =  ");
		String str1 = sc.nextLine();
		
		System.out.println("Original String = " + str1);
		int i = 0; 
		
		while(i < str1.length())
		{
			if(str1.charAt(i) != ' ' && str1.charAt(i) != '\t')
			{
				strBuffer.append(str1.charAt(i));
			}
			i++;
		}
		
		System.out.println("Final String = " + strBuffer.toString());
	}
}
Enter String to Remove White Spaces =  hello java programming world
Original String = hello java programming world
Final String = hellojavaprogrammingworld