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

Java program To Reverse String without function

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
 
package com.spy.javaforlearn;
 
import java.util.Scanner;
 
public class Reverse 
{
 
	public static void main(String[] args) 
	{
 
		//Defining scanner class to take input from user
		Scanner scn=new Scanner(System.in);
 
		System.out.println("Enter a String");
 
		//Taking input of type string from user
		String s=scn.nextLine();
 
 
		// String object to store Reverse String
		String rev=" ";
 
 
		// calculating length of input String
		int length=s.length();
 
 
		// getting last index of string and storing into String Rev
 
		for(int i=length-1;i>=0;i--)
		{
 
			rev=rev+s.charAt(i);
		}
 
		System.out.println("Reverse of String: "+rev);
 
	}
}

output:

1
2
3
4
 
Enter a String
Bhavesh
Reverse of String:  hsevahB