Write a Java program to remove all whitespaces from a string with an example. In this language, we can use the 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); } }
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 a character array. Next, for(int i =0; i < strArray.length; i++) iterate the characters.
The If statement if(strArray[i] != ‘ ‘ && strArray[i] != ‘\t’) filters the non-empty characters. Then, append those non-empty characters to a Java stringbuffer.
package NumPrograms; import java.util.Scanner; public class StRemWhiteSp2 { private static Scanner sc; public static void main(String[] args) { sc= new Scanner(System.in); StringBuffer strBuffer = new StringBuffer(); System.out.print("Enter Text = "); String str1 = sc.nextLine(); System.out.println("Original = " + 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 = " + strBuffer.toString()); } }
Enter Text = learn favourite programs for free
Original = learn favourite programs for free
Final = learnfavouriteprogramsforfree
Java Program to remove all whitespaces from a string using a while loop
package NumPrograms; import java.util.Scanner; public class StRemWhiteSp3 { private static Scanner sc; public static void main(String[] args) { sc= new Scanner(System.in); StringBuffer strBuffer = new StringBuffer(); System.out.print("Enter Text = "); String str1 = sc.nextLine(); System.out.println("Original = " + 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 = " + strBuffer.toString()); } }
Enter Text = hello programming world
Original = hello programming world
Final = helloprogrammingworld