我有我创建的代码来做到这一点,但是我的问题是有一种方法可以改进我的代码。似乎有更好的方法来解决这个问题。
public static IEnumerable<string> SplitEvery(this string str, int chunkSize, bool splitAtSpaces)
{
var chars = str.ToCharArray();
var i = 0;
var currentString = string.Empty;
var nextWord = false;
while (i < chars.Length)
{
if (nextWord)
{
currentString = string.Empty;
nextWord = false;
}
if (currentString.Length < chunkSize)
{
currentString += chars[i];
if ((i + 1) == chars.Length)
yield return currentString;
i++;
}
else
{
if (splitAtSpaces)
{
var charAtEnd = currentString[currentString.Length - 1];
if (charAtEnd == ' ' || chars[i] == ' ')
{
nextWord = true;
yield return currentString;
}
else
{
var lastSpace = currentString.LastIndexOf(' ');
i = lastSpace + 1;
nextWord = true;
yield return currentString.Substring(0, i);
}
}
else
{
nextWord = true;
yield return currentString;
}
}
}