In this post, you will learn two ways to remove whitespace from Java strings. One is to use built-in methods that are useful when developing applications, and the other is to not use built-in methods.
Examples:
Input : str = " Proedu Java tutorial " Output : ProeduJavatutorial
Example – Program to remove all white space from String using built-in method
public class RemoveWhiteSpace { public static void main(String[] args) { String whiteSpaceStr = " Proedu Java tutorial "; whiteSpaceStr = whiteSpaceStr.replaceAll("\\s", ""); System.out.println(whiteSpaceStr); } }
Output
ProeduJavatutorial
Example – Without Using Built-In Methods
public class RemoveWhiteSpace { public static void main(String[] args) { String whiteSpaceStr = " Proedu Java tutorial "; char[] strArray = whiteSpaceStr.toCharArray(); String stringWithoutSpaces = ""; for (int i = 0; i < strArray.length; i++) { if ((strArray[i] != ' ') && (strArray[i] != '\t')) { stringWithoutSpaces = stringWithoutSpaces + strArray[i]; } } System.out.println("String :" + whiteSpaceStr); System.out.println("String Without Spaces :" + stringWithoutSpaces); } }
Output
String : Proedu Java tutorial String Without Spaces :ProeduJavatutorial