In this Java tutorial, you will learn how to remove whitespace characters in string using String.replace() method, with examples.

Remove Whitespaces in the String in Java

To remove white spaces in a string in Java, you can use regular expression that represents white space characters and replace them with required character or empty string.

Sometimes, your text file may contain more than one new line characters between lines. Or more than one spaces between words. And you would like to clean the content using string operations in Java.

In this tutorial, we will learn how to identify and remove white spaces in a string.

Examples

ADVERTISEMENT

1. Remove all whitespace characters in string

In this example, we will remove all the white-spaces in a string using String.replace() function.

/**
 * Java Example Program, to remove white spaces from string
 */

public class RemoveSpaces {

	public static void main(String[] args) {
		String str1 = "Hi! Good      morning.\nHave a good day.   ";
		
		//remove white spaces
		String resultStr = str1.replaceAll("\\s", "");
		
		System.out.print(resultStr);
	}
}

Run the program. All white spaces in the string: spaces between the words, leading spaces, trailing spaces, and all spaces shall be removed from the string.

Hi!Goodmorning.Haveagoodday.

2. Remove all new-line characters from string

In this example, we will remove all the new-line characters, but not worry about other white space characters.

/**
 * Java Example Program, to remove white spaces from string
 */

public class RemoveSpaces {

	public static void main(String[] args) {
		String str1 = "Hi! Good      morning.\nHave a good day.   ";
		
		//remove white spaces
		String resultStr = str1.replaceAll("\n", "");
		
		System.out.print(resultStr);
	}
}

Run the program.

Hi! Good      morning.Have a good day.

The new-line character between the string has been removed.

Conclusion

In this Java Tutorial, we learned how to remove white space characters from a string using regular expression and escape characters of white space characters and String.replaceAll() function.