title: Manually trimming a string in Java (without String.trim())
body: <p>I was playing around with the idea of doing this without using <code>String.trim()</code>. I made a method that trims leading and trailing spaces, which is shown below:</p>
  
  <pre><code>public static String removeLeadingAndTrailingSpaces(String s) {
      StringBuilder sb = new StringBuilder();
      int i = 0;
  
      while (s.charAt(i) == ' ') {
          i++;
      }
  
      for (; i &lt; s.length(); i++) {
          sb.append(s.charAt(i));
      }
  
      // aux is the string with only leading spaces removed
      String aux = sb.toString();
      int j = aux.length() - 1;
  
      while (aux.charAt(j) == ' ') {
          j--;
      }
  
      // now both leading and trailing spaces have been removed
      String result = aux.substring(0, j + 1);
  
      return result;
  }
  </code></pre>
  
  <p>I've tested it and it works 100%. But, I'm not convinced this is the most efficient or practical implementation. How else could I have done it? I feel it could be done without using the extra variables <code>aux</code> and <code>j</code>, but I couldn't come up with a way for it.</p>