LINQ - Splitting up a string with maximum length, but not chopping words apart.

Posted by Stacey on Stack Overflow See other posts from Stack Overflow or by Stacey
Published on 2010-12-29T17:12:23Z Indexed on 2010/12/29 17:53 UTC
Read the original article Hit count: 203

Filed under:
|

I have a simple LINQ Extension Method...

    public static IEnumerable<string> SplitOnLength(this string input, int length)
    {
        int index = 0;
        while (index < input.Length)
        {
            if (index + length < input.Length)
                yield return input.Substring(index, length);
            else
                yield return input.Substring(index);

            index += length;
        }
    }

This takes a string, and it chops it up into a collection of strings that do not exceed the given length.

This works well - however I'd like to go further. It chops words in half. I don't need it to understand anything complicated, I just want it to be able to chop a string off 'early' if cutting it at the length would be cutting in the middle of text (basically anything that isn't whitespace).

However I suck at LINQ, so I was wondering if anyone had an idea on how to go about this. I know what I am trying to do, but I'm not sure how to approach it.

So let's say I have the following text.

This is a sample block of text that I would pass through the string splitter.

I call this method SplitOnLength(6) I would get the following.

  • This i
  • s a sa
  • mple b
  • lock o
  • f text
  • that I
  • would
  • pass t
  • hrough
  • the s
  • tring
  • splitt
  • er.

I would rather it be smart enough to stop and look more like ..

  • This
  • is a
  • sample

// bad example, since the single word exceeds maximum length, but the length would be larger numbers in real scenarios, closer to 200.

Can anyone help me?

© Stack Overflow or respective owner

Related posts about c#

Related posts about LINQ