gpt4 book ai didi

c# - 将大文本字符串拆分为可变长度的字符串,而不打断单词并保留换行符和空格

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

我试图将一个大文本字符串分成几个较小的文本字符串,并将每个较小的文本字符串的最大长度定义为不同。例如:

"The quick brown fox jumped over the red fence.
The blue dog dug under the fence."

我想要的代码可以将其拆分为更小的行,并且第一行最多有 5 个字符,第二行最多有 11 个字符,其余最多有 20 个字符,结果是:

Line 1: The 
Line 2: quick brown
Line 3: fox jumped over the
Line 4: red fence.
Line 5: The blue dog
Line 6: dug under the fence.

所有这一切都在 C# 或 MSSQL 中,这可能吗?

最佳答案

public List<String> SplitString(String text, int [] lengths)
{
List<String> output = new List<String>();

List<String> words = Split(text);

int i = 0;
int lineNum = 0;
string s = string.empty;
while(i<words.Length)
{
if(s.Length+words[i].Length <lengths[lineNum])
{
s+=words[i];
i++;
if(lineNum<lengths.Length-1)
lineNum++;
}
else
{
output.Add(s);
s=String.Empty;
}

}

s.Remove(S.length-1,1);// deletes last extra space.

return output;
}


public static List<string> Split(string text)
{
List<string> result = new List<string>();
StringBuilder sb = new StringBuilder();

foreach (var letter in text)
{
if (letter != ' ' && letter != '\t' && letter != '\n')
{
sb.Append(letter);
}
else
{
if (sb.Length > 0)
{

result.Add(sb.ToString());
}

result.Add(letter.ToString());
sb = new StringBuilder();
}
}

return result;
}

这是未经测试/编译的代码,但您应该明白了。

我也认为您应该改用 StringBuilder,但我不记得如何使用它。

关于c# - 将大文本字符串拆分为可变长度的字符串,而不打断单词并保留换行符和空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2815021/

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