Write a java program to remove all white spaces from a string.?

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[i] != ' ') && (strArray[i] != '\t') )
            {
                sb.append(strArray[i]);
            }
        }
 
        System.out.println(sb);           //Output : CoreJavajspservletsjdbcstrutshibernatespring
    }
}

 

Share

Recent Posts

How to reverse Singly Linked List?

[crayon-663770fd98560281924553/] [crayon-663770fd98569190998923/] Output: Adding: 3 Adding: 32 Adding: 54 Adding: 89 3 32 54 89…

5 years ago

Find out duplicate number between 1 to N numbers.

[crayon-663770fd98636153194035/]

5 years ago

Find out middle index where sum of both ends are equal

You are given an array of numbers. Find out the array index or position where…

5 years ago

Write a singleton class in Java

Singleton class means you can create only one object for the given class. You can…

5 years ago

Write a java program to reverse a string?

1) Using StringBuffer class In this method, we use reverse() method of StringBuffer class to reverse the…

5 years ago

Singly linked list implementation

Singly Linked Lists are a type of data structure. It is a type of list.…

5 years ago