A loop is certainly the way to go. The algorithm you describe should work fine. This can be done quite elegantly using an iterator block. Read more about iterator blocks and the yield return
construct here. You could also make the method into an extension method so that it would look something like this:
public static IEnumerable<string> NewSplit(this string @this, int lineLength) {
var currentString = string.Empty;
var currentWord = string.Empty;
foreach(var c in @this)
{
if (char.IsWhiteSpace(c))
{
if(currentString.Length + currentWord.Length > lineLength)
{
yield return currentString;
currentString = string.Empty;
}
currentString += c + currentWord;
currentWord = string.Empty;
continue;
}
currentWord += c;
};
// The loop might have exited without flushing the last string and word
yield return currentString;
yield return currentWord;
}
Then, this can be invoked like the normal Split
method:
myString.NewSplit(10);
One of the benefits of iterator blocks is that they allow you to perform logic after an element is returned (the logic right after the yield return
statements). This allows the programmer to write the logic the way he or she is probably thinking about the problem.