title: Best way to split string into lines with maximum length, without breaking words
body: <p>I want to break a string up into lines of a specified maximum length, without splitting any words, if possible (if there is a word that exceeds the maximum line length, then it will have to be split). </p>
  
  <p>As always, I am acutely aware that strings are immutable and that one should preferably use the StringBuilder class. I have seen examples where the string is split into words and the lines are then built up using the StringBuilder class, but the code below seems "neater" to me.</p>
  
  <p>I mentioned "best" in the description and not "most efficient" as I am also interested in the "eloquence" of the code. The strings will never be huge, generally splitting into 2 or three lines, and it won't be happening for thousands of lines. </p>
  
  <p>Is the following code really bad?</p>
  
  <pre><code>private static IEnumerable&lt;string&gt; SplitToLines(string stringToSplit, int maximumLineLength)
  {
      stringToSplit = stringToSplit.Trim();
      var lines = new List&lt;string&gt;();
  
      while (stringToSplit.Length &gt; 0)
      {
          if (stringToSplit.Length &lt;= maximumLineLength)
          {
              lines.Add(stringToSplit);
              break;
          }
  
          var indexOfLastSpaceInLine = stringToSplit.Substring(0, maximumLineLength).LastIndexOf(' ');
          lines.Add(stringToSplit.Substring(0, indexOfLastSpaceInLine &gt;= 0 ? indexOfLastSpaceInLine : maximumLineLength).Trim());
          stringToSplit = stringToSplit.Substring(indexOfLastSpaceInLine &gt;= 0 ? indexOfLastSpaceInLine + 1 : maximumLineLength);
      }
  
      return lines.ToArray();
  }
  </code></pre>