Advertisement
sweet1cris

Untitled

Sep 21st, 2017
64
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.04 KB | None | 0 0
  1. public class RemoveSpaces {
  2.   // Assumption: input is not null.
  3.   public String removeSpaces(String input) {
  4.     if (input.isEmpty()) {
  5.       return input;
  6.     }
  7.     char[] array = input.toCharArray();
  8.     int end = 0;
  9.     for (int i = 0; i < array.length; i++) {
  10.       // when we would ignore the current space character:
  11.       // 1. we ignore all the space characters followed by
  12.       // another space character, so that if there are several
  13.       // consecutive space characters, only the first one will
  14.       // be remained.
  15.       // 2. we ignore also the space character if it is the
  16.       // first character of the input string.
  17.       if (array[i] == ' ' && (i == 0 || array[i - 1] == ' ')) {
  18.         continue;
  19.       }
  20.       array[end++] = array[i];
  21.     }
  22.     // Post-processing: it is possible we still have one trailing
  23.     // space character at the end.
  24.     if (end > 0 && array[end - 1] == ' ') {
  25.       return new String(array, 0, end - 1);
  26.     }
  27.     return new String(array, 0, end);
  28.   }
  29. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement