How to exclude white spaces

Asked

Viewed 2,062 times

2

Example

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

Upshot
"text with white spaces"

  • at the ends with String#trim(), already have a recent question about him.

  • It is not only in the extremities, but also the spaces too.

2 answers

4

You can use a regular expression:

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

Upshot

text with white spaces

To also remove the 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 regular expression \s corresponds to any blank character.

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

This information is then passed to the Replaceall function which replaces the consecutive spaces found, with only one blank.

Stay here the example and the source.

  • I was just about to comment on that, I was getting some space behind the edges.

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);
  • Please collaborate with the quality of community content by better elaborating your response. Very short answers will hardly be clear enough to add anything to the discussion. If your response is based on some function or feature of the language/tool, link to the official documentation or reliable material that supports your response. Searching for similar questions in the community can also be interesting to indicate other approaches to the problem.

  • Scanner is a class of Java, https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html

  • Do not add explanations to the comments. Go to [Edit] and supplement your original response. And not only reference the documentation, explain what your code does with words. What may be trivial, for other users it may not be.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.