gpt4 book ai didi

c# - 如何在不拆分单词的情况下将字符串拆分为List

转载 作者:太空宇宙 更新时间:2023-11-03 17:58:51 24 4
gpt4 key购买 nike

假设我们有一个长字符串,希望将其拆分为64个字符长的字符串,而不拆分单个单词:

We prefer questions that can be answered, not just discussed. If your question is about this website, ask it on meta instead.


如果我们这样分割:

string.SplitByLength(64).ToList();


我们将以两个字符串结尾:

We prefer questions that can be answered, not just discussed. I
f your question is about this website, ask it on meta instead.


拆分此字符串以使第一个字符串在 If之前结束而第二个字符串以 If开头的最优雅的方法是什么?

换句话说,如何将长字符串拆分为等于或小于所需长度的字符串列表,而不拆分任何单个单词,而是在单词之间的最后一个空白处进行拆分?

最佳答案

您可以给它一个最大值,例如64,然后将其用作索引以向后搜索并找到第一个空格并在那里分割。使用递归在其余字符串上重复操作,您已完成。

public static IEnumerable<string> SmartSplit(this string input, int maxLength)
{
int i = 0;
while(i + maxLength < input.Length)
{
int index = input.LastIndexOf(' ', i + maxLength);
if(index<=0) //if word length > maxLength.
{
index=maxLength;
}
yield return input.Substring(i, index - i);

i = index + 1;
}

yield return input.Substring(i);
}

关于c# - 如何在不拆分单词的情况下将字符串拆分为List <string>?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4879522/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com