I need a function that looks like this
static IEnumerable<string> GetSplittedSentences(string str, int iterateCount)
{
var words = new List<string>();
for (int i = 0; i < str.Length; i += iterateCount)
if (str.Length - i >= iterateCount)
words.Add(str.Substring(i, iterateCount));
else
words.Add(str.Substring(i, str.Length - i));
return words;
}
Credits to Split string by character count and store in string array
I pass in a string that is a sentence, and an Int which is the max number of characters allowed in a sentence.
But the issue is: I don't want the sentence to be split in middle of a word. Instead split before the last possible word and go to the next sentence.
I couldn't figure out how to do that. Does anybody know how?
Thank you in advance
Let's try it. (following the second option in the Juharr comment above)
static IEnumerable<string> GetSplittedSentences(string str, int iterateCount)
{
var words = new List<string>();
int i = 0;
while(i < str.Length)
{
// Find the point where the split should occur
int endSentence = i+iterateCount;
if (endSentence <= str.Length)
{
// Go back to find a space
while(str[endSentence] != ' ')
endSentence--;
// Take the string before the space
words.Add(str.Substring(i, endSentence-i));
// Position the start point to extract the next block
i = endSentence+1;
}
else
{
words.Add(str.Substring(i, str.Length - i));
i = str.Length; // Force the loop to exit
}
}
return words;
}
Still this will have problems if there is a word with a length bigger than iterateCount