0

I want a clean looking function that will remove all whitespace that comes before and after a "block" of text/characters. So, if I have a string like:

  • "The barn ": Needs to become "The barn".

  • " The barn": Needs to become "The barn".

  • " The barn is small ":

    Needs to become "The barn is small"

Etc. A "block of text" is essentially everything between the first non-whitespace character and the last non-whitespace character.

I was thinking of looping through a string:

  1. Until I encounter a non-whitespace character, I throw everything away.
  2. Once I encounter a non-whitespace character, I start saving it to a string I'll be returning.
  3. If I encounter a whitespace again, I save it to a temporary variable.
  4. If I encounter a non-whitespace character, I append the temp variable to the string i'll be returning, then repeat from step 3.
  5. If I don't encounter a non-whitespace character, I can discard the temp string and just return the string I've been saving.

I feel like this might be a bit messy though and could be done more elegantly? Maybe with some regex? Although I would agree that regex being less messy is really just a matter of opinion.

Community
  • 1
  • 1
John Lexus
  • 3,014
  • 3
  • 12
  • 28
  • @DavidKroukamp trim would only remove whitespace at the head and tail of the string, not between. – Jason Jun 18 '20 at 00:02
  • @Jason trim() is what I want, actually, as I want to remove all leading and trailing spaces, but none of the spaces that are actually between the string. Thanks, I thoght trim did something else entirely. – John Lexus Jun 18 '20 at 00:05
  • @JohnLexus interesting, i *thought* you wanted to remove space in between as well, apologies. – Jason Jun 18 '20 at 00:08
  • 1
    Since Java 11 we also have `strip()` method. See [Difference between String trim() and strip() methods in Java 11](https://stackoverflow.com/q/51266582) – Pshemo Jun 18 '20 at 00:09
  • @Pshemo thanks for this, very interesting, think it's better to use strip() then – John Lexus Jun 20 '20 at 03:36

0 Answers0