How to remove all whitespace from String in Java?

There are multiple way to remove all whitespace from String in Java.

replaceAll() :- public String replaceAll(String regex, String replacement)
This method replaces all the substrings of the string matching the specified regex expression with the specified replacement text.
To remove spaces i.e., trailing or leading, or we are specify the regex expression.

syntax:- \s                                         description:- To remove all space

for loop() :- here first we convert String into character array from toCharArray method.then we create stringbuffer class make one for loop and pass to character array data.inside for loop there will be one if condition that will check space will not equal to character value at depend on the index.after that we store all character inside string buffer.

					public class RemoveWhiteSpace {
	public static void main(String[] args) {

		String str = " core java servlet ";
		String ht = str.replaceAll("\\s", "");
		System.out.println("Replace all using regex :- " + ht);

		String value = "welcome to springboot";
		char[] ch = value.toCharArray();
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < ch.length; i++) {
			if (ch[i] != ' ') {
		System.out.println("using for for loop and char method:- " + sb);

Output :-
Replace all using regex :- corejavaservlet
using for for loop and char method:- welcometospringboot

Leave a Comment

Your email address will not be published. Required fields are marked *