title: How to Improve Split Every nth character AND not cut off words
body: <p>I have code that I've created to do exactly this, however my question is there a way I can improve my code. It seems like there may be a better way to take care of this.</p>
  
  <pre><code>public static IEnumerable&lt;string&gt; SplitEvery(this string str, int chunkSize, bool splitAtSpaces)
      {
          var chars = str.ToCharArray();
  
          var i = 0;
          var currentString = string.Empty;
  
          var nextWord = false;
  
          while (i &lt; chars.Length)
          {
              if (nextWord)
              {
                  currentString = string.Empty;
                  nextWord = false;
              }
  
              if (currentString.Length &lt; chunkSize)
              {
                  currentString += chars[i];
                  if ((i + 1) == chars.Length)
                      yield return currentString;
                  i++;
              }
              else
              {
                  if (splitAtSpaces)
                  {
                      var charAtEnd = currentString[currentString.Length - 1];
  
                      if (charAtEnd == ' ' || chars[i] == ' ')
                      {
                          nextWord = true;
                          yield return currentString;
                      }
                      else
                      {
                          var lastSpace = currentString.LastIndexOf(' ');
                          i = lastSpace + 1;
                          nextWord = true;
                          yield return currentString.Substring(0, i);
                      }
                  }
                  else
                  {
                      nextWord = true;
                      yield return currentString;
                  }
              }
          }
  </code></pre>