How to exclude white space

2

Example

String str = "  texto com     espaços   em     branco           ";

Result
    "text with spaces"

    
asked by anonymous 09.05.2017 / 22:57

2 answers

3

You can use a regular expression:

System.out.println("  texto com   espaços   em  branco".replaceAll("\s+", " "));

Result

  

Text with blanks

To also remove spaces at the ends, you can first apply the trim () function:

System.out.println("  texto com   espaços em  branco".trim().replaceAll("\s+", " "));

The idea is that the regular expression \s matches any white space character.

If any pattern is followed by a +, it means that this pattern needs to appear 1 or more times. In this case, \ s +, matches with one or more consecutive blanks.

This information is then passed to the ReplaceAll function that replaces the consecutive spaces found, with only one blank space.

Here's the example and font .

    
09.05.2017 / 23:06
0

You can use the Scanner class

    Scanner s = new Scanner(text);
    String t = null;
    while (s.hasNext()) {
        if(t == null)
            t = s.next();
        else
            t = t +" "+s.next();
    }       
    System.out.println(t);
    
09.05.2017 / 23:15