1

I'm trying to replace all sequences of two or more whitespaces in a string with a single space.

I've already got it using the String.trim().replaceAll(" +", " ") method.

But I was trying to figure it out on my own using what I knew, and I got close, wondering if anyone can fix what I have to make it work.

Here's what I was trying:

StringBuilder sampleTextBuilder = new StringBuilder(sampleText);
for (int i = 0; i < sampleTextBuilder.length(); i++) {
            if (Character.isLetter(sampleTextBuilder.charAt(i))) {
                isLetter = true;
                isFirstWS = false;
            }
            else if (Character.isWhitespace(sampleTextBuilder.charAt(i)) && isLetter) {
                isFirstWS = true;
                isLetter = false;
            }
            else if (Character.isWhitespace(sampleTextBuilder.charAt(i)) && isFirstWS)  {
                sampleTextBuilder.deleteCharAt(i);
            }
            sampleText = sampleTextBuilder.toString();
}
  • Does this answer your question? [Java how to replace 2 or more spaces with single space in string and delete leading and trailing spaces](https://stackoverflow.com/questions/2932392/java-how-to-replace-2-or-more-spaces-with-single-space-in-string-and-delete-lead) – sleepToken Dec 06 '19 at 18:03
  • Yes, that's what I used. I wanted to see if there was a way to do it like this tho. @WJS nailed it. – Jonsnowsbumps Dec 06 '19 at 23:46

1 Answers1

0

You don't really need the booleans. Just keep track of the indices. Keep in mind that removing characters one at a time is expensive because there is quite a bit of array copying under the hood with these StringBuilder methods.

One more subtlety. When you iterate from the beginning and delete characters, all characters move to the left one spot. This can require additional bookkeeping. To solve this you iterate from the right. Then when you delete a character, it doesn't affect the relative positions of the characters further to the left.

      String sampleText = "This    is    a  test of    removing extra spaces";
      StringBuilder sampleTextBuilder = new StringBuilder(sampleText);
      for (int i = sampleTextBuilder.length() - 1; i >= 0; i--) {
         if (sampleTextBuilder.charAt(i) == ' ') {
            // found a space, check front and back of string.
            if (i == sampleTextBuilder.length() - 1 || i == 0) {
               sampleTextBuilder.deleteCharAt(i);
            }
            // otherwise, delete one of them if two are present.
            else if (sampleTextBuilder.charAt(i - 1) == ' ') {
               sampleTextBuilder.deleteCharAt(i - 1);
            }
         }
      }
      sampleText = sampleTextBuilder.toString();
      System.out.println("\"" + sampleText + "\"");

WJS
  • 36,363
  • 4
  • 24
  • 39