如果有一定数量的字符,则拆分句子
Split sentence if it has certain number of characters
我需要一个看起来像这样的函数
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;
}
感谢Split string by character count and store in string array
我传入一个字符串,它是一个句子,还有一个Int
,这是一个句子中允许的最大字符数。
但问题是:我不希望句子在单词中间被拆分。而是在最后一个可能的单词之前拆分并转到下一个句子。
我不知道该怎么做。有人知道怎么做吗?
提前致谢
我们来试试吧。 (按照上面 Juharr 评论中的第二个选项)
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;
}
如果有一个词的长度大于iterateCount
,这仍然会有问题
我需要一个看起来像这样的函数
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;
}
感谢Split string by character count and store in string array
我传入一个字符串,它是一个句子,还有一个Int
,这是一个句子中允许的最大字符数。
但问题是:我不希望句子在单词中间被拆分。而是在最后一个可能的单词之前拆分并转到下一个句子。
我不知道该怎么做。有人知道怎么做吗?
提前致谢
我们来试试吧。 (按照上面 Juharr 评论中的第二个选项)
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;
}
如果有一个词的长度大于iterateCount
,这仍然会有问题