Skip to main content

How to Remove White space in String in Java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
 
package com.spy.javaforlearn;
 
import java.util.Scanner;
 
public class RemoveWhiteSpace 
{
 
	public static void main(String[] args) 
 
	{
 
		try
 
		{
 
		System.out.println("Enter the String.");
		Scanner scan = new Scanner(System.in);
 
		String str = scan.nextLine();
 
 
		//Using ReplaceAll method of String class
 
		System.out.println("**********With ReplaceAll Method***********");
 
		System.out.println("String without whitespace is : "+str.replaceAll(" ",""));
 
		//Without using ReplaceAll method
 
		System.out.println("**********Without ReplaceAll Method*********");
 
		char[] strarr = str.toCharArray();
 
		StringBuffer strbuf = new StringBuffer();
 
 
		for(int i=0; i<strarr.length;i++)
		{
 
			if(strarr[i] != ' '){
			strbuf.append(strarr[i]);}
		}
 
 
		System.out.println("String without whitespace is : "+strbuf);
		scan.close();
 
		}
		catch(Exception e)
		{
		   e.printStackTrace();
	    }
	}
}

output:

1
2
3
4
5
6
7
 
Enter the String.
Hi Hello Bhavesh
**********With ReplaceAll Method***********
String without whitespace is : HiHelloBhavesh
**********Without ReplaceAll Method*********
String without whitespace is : HiHelloBhavesh