I want to split a string by a certain length, but I also want to make sure that it's a full word. For example, if I had:
string str = "Hello I have a dog ";
and I wanted to split it up into chunks of 5 I would do something like this (which I got from Split String into smaller Strings by length variable):
public IEnumerable<string> SplitByLength( string s, int length)
{
for (int i = 0; i < s.Length; i += length)
{
if (i + length <= s.Length)
{
yield return s.Substring(i, length);
}
else
{
yield return s.Substring(i);
}
}
}
but that would result in output like
"Hello"
"I Hav"
"e a d"
"og"
How could I adapt it so that it would split after 5 or after a whitespace? So I would get:
"Hello"
"I"
"Have"
It's not the best example but it's the best I could come up with off the top of my head. The reason I need it is that I'm displaying the results on a web page, and after a certain amount of words, it gets difficult to read due to a background image, so when it hits the limit it breaks a line but I don't want half of a word on one line and the other half on the next line.