DEV Community

Lalit Kumar
Lalit Kumar

Posted on

How to remove whitespaces from a string in java

In this article, we will learn how to remove spaces from a string in java
In thisblog, we will learn how to remove the whitespace from a string in java. One method uses a brand built-in method that will be useful when you are developing applications and other methods do not use the built-in methods that will help to interview you. Because, in the interview, the interviewer always asks to not use the built-in method while testing your coding skills

How to Remove White Spaces Of String in Java Using Built-In Methods?

In the first method, we use the method replaceAll () of the String class to remove all whitespace (including tabs as well) from the string. It is one of the easiest ways to remove the spaces from the string in java. replaceAll () method takes two parameters. One of them is the string to be replaced and another one is the string that will be replaced with. We passed the string "\ s +" to be replaced with an empty string "". This method removes spaces at the end, the space at the beginning and a space between the words.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21


title: "originally posted here 👇"

canonical_url: https://kodlogs.com/blog/2204/how-to-remove-spaces-from-a-string-in-java

Program

java.util.Scanner import;

Public class RemoveWhiteSpaces
{
    public static void main (String [] args)
    {
        Scanner sc = new Scanner (System.in);

        System.out.println ( "Enter input string to be cleaned of the white space ...!");

        String inputString = sc.nextLine ();

        String stringWithoutSpaces = inputString.replaceAll ( " s +", "");

        System.out.println ( "Input String:" + inputString);

        System.out.println ( "String Input Without Spaces:" + stringWithoutSpaces);

        sc.close ();
    }
}
Enter fullscreen mode Exit fullscreen mode

output:

Enter input string to be cleaned of the white space ...!
One space TwoSpaces ThreeSpaces FourSpaces Tab End
String input: one space TwoSpaces ThreeSpaces FourSpaces Tab End
Put String Without Spaces: OneSpaceTwoSpacesThreeSpacesFourSpacesTabEnd

Note:

"\ s +" Vs "\ s": Both of these strings, when passing to replaceAll () method, produce the same results with similar performance. But, when the number of consecutive rising space, "\ s +" is a little faster than the "\ s". Because, replacing some space set in a row
with the replacement string at a time rather than replacing one by one.
trim () method trims string given mis eliminate white space at the beginning and at the end of the string, not the words.
Find more in original post

Top comments (0)