Remove all white spaces from a string in java

What is String?, Declare String Variables, Compare Strings, Concatenate Strings, Read Data and Covert String type data to Integer type and Double Type.
Post Reply
charan
Posts: 48
Joined: Fri Nov 23, 2018 5:31 am

Remove all white spaces from a string in java

Post by charan » Thu Dec 06, 2018 5:46 am

How do you remove all white spaces from a string in java?

ramya
Posts: 89
Joined: Fri Nov 23, 2018 2:55 am

Re: Remove all white spaces from a string in java

Post by ramya » Thu Dec 06, 2018 5:49 am

1) Using replaceAll() Method.

In the first method, we use replaceAll() method of String class to remove all white spaces (including tab also) from a string. This is the one of the easiest method to remove all white spaces from a string. This method takes two parameters. One is the string to be replaced and another one is the string to be replaced with. We pass the string “\s” to be replaced with an empty string “”.

2) Without Using replaceAll() Method.

In the second method, we remove all white spaces (including tab also) from a string without using replaceAll() method. First we convert the given string to char array and then we traverse this array to find white spaces. We append the characters which are not the white spaces to StringBuffer object.

Here is the java program which uses both the methods to remove white spaces from a string.

class RemoveWhiteSpaces
{
public static void main(String[] args)
{
String str = " Core Java jsp servlets jdbc struts hibernate spring ";

//1. Using replaceAll() Method

String strWithoutSpace = str.replaceAll("\\s", "");

System.out.println(strWithoutSpace); //Output : CoreJavajspservletsjdbcstrutshibernatespring

//2. Without Using replaceAll() Method

char[] strArray = str.toCharArray();

StringBuffer sb = new StringBuffer();

for (int i = 0; i < strArray.length; i++)
{
if( (strArray != ' ') && (strArray != '\t') )
{
sb.append(strArray);
}
}

System.out.println(sb); //Output : CoreJavajspservletsjdbcstrutshibernatespring
}
}

Post Reply

Return to “Java Strings”