title: C++ Implementation to Trim Char Array of Leading/Trailing White Space Not Working As Expected
body: <p>I am trying to implement a simple and safe way to trim a char array of both leading and trailing white space. It works to remove the leading white space, but isn't working for the other side. Can anyone see what I am doing wrong? Here is my code:</p>
  
  <pre><code>template&lt;size_t charCount&gt;
  void strtrim_safe( char (&amp;output)[charCount] ) {
    char *ptr = output;
    size_t n = charCount;
    size_t start = 0;
    size_t end = 0;
  
    // Find the start and end position of trimmed string
    while ( n-- != 0 &amp;&amp; *ptr != 0 ) {
      if ( *ptr == 32 ) {
          if ( end == 0 ) {
              start++;
          } else {
              break;
           }
      } else {
          end++;
      }
  
      ptr++;
    }
  
    // Shift the char array 
    for ( int i = start, j =  0; i &lt; end, j &lt; charCount; i++, j++ ) {
        output[j] = output[i];
    }
  }
  </code></pre>
  
  <p>Thanks in advance!</p>
  
  <p>EDIT1:
  Thanks to your input, I think I have fixed the issue. The following code in place of the code under Shift the char array seems to do the trick:</p>
  
  <pre><code>// Shift the char array 
  for ( int i = start, j =  0; i &lt; end + start &amp;&amp; j &lt; charCount; i++, j++ ) {
      output[j] = output[i];
  }
  output[end] = 0;
  </code></pre>
  
  <p>Tested with trailing white space only, leading white space only, white space on both sides, and of course, no white space. So far, so good</p>
  
  <p>EDIT2:
  In order to account for possible interior spaces, I did the checking within the while loop and came up with this:</p>
  
  <pre><code>template&lt;size_t charCount&gt;
  void strtrim_safe( char (&amp;output)[charCount] ) {
     char *ptr = output;
     size_t n = charCount;
     size_t start = 0;
     size_t end = 0;
  
     // Find the start and end position of trimmed string
     while ( n-- != 0 &amp;&amp; *ptr != 0 ) {
        if ( *ptr == 32 ) {
          if ( end == 0 ) {
              start++;
          } else {
            size_t endTmp = end;
            while ( *ptr == 32 &amp;&amp; n-- != 0 &amp;&amp; *ptr != 0 ) {
              end++;
              ptr++;
            }
          if ( *ptr == 0 || n == 0 ) {
            end = endTmp;
          } else {
            end++;
          }
        }
      } else {
        end++;
      }
  
      ptr++;
    }
  
    // Shift the char array 
    for ( int i = start, j =  0; j &lt; end + start &amp;&amp; j &lt; charCount; i++, j++ ) {
      output[j] = output[i];
    }
    output[end] = 0;
  }
  </code></pre>