title: Replace spaces with tab character
body: <p>I just finished the first chapter of <em>The C Programming Language</em> and there are a few exercises before moving on. I already completed the one to replace the tab character with spaces which was fairly easy, but I am stuck on the one to replace space characters with the proper amount of tabs and spaces to achieve the same spacing. </p>
  
  <p>My implementation "sometimes" works, so essentially it doesn't work. Here is the function:</p>
  
  <pre><code>#define TABLEN 5
  
  // entab: replace consecutive spaces of length TABLEN with the tab character
  void entab(char string[])
  {
      int i, consec;
      int to, from, tabloc;
  
      consec = 0;
      for (i = 0; string[i] != '\0'; ++i) {
          // count consecutive spaces in a string
          if (string[i] == ' ') ++consec;
          else consec = 0;
  
          if (consec &gt;= TABLEN) {
              // set location to insert tab character
              tabloc = (i - TABLEN) + 1;
  
              for (to = tabloc, from = i;
                  string[from] != '\0'; ++from, ++to)
              {
                  // replace space characters
                  string[to] = string[from];
              }
  
              string[tabloc] = '\t';
              string[to] = '\0';
              i = tabloc;
              consec = 0;
          }
      }
  }
  </code></pre>
  
  <p>This function is extremely inconsistent in working successfully to the point where there isn't even a pattern of when it does and doesn't work. By "doesn't work", I mean one of two situations. 1.) the spaces are deleted and no tab character is inserted, or 2.) the spaces are deleted, a tab character is inserted, but somehow an extra space is added in. These issues have led me to realize that the problem exists in the loop that replaces the spaces, but I'm so new to C that I have no idea what is wrong. Can someone point me in the right direction here? </p>