gpt4 book ai didi

c# - 将长字符串分成 60 个字符的长行但不要打断单词

转载 作者:太空狗 更新时间:2023-10-30 00:47:01 25 4
gpt4 key购买 nike

必须有更好的方法来做到这一点。我只想将长字符串拆分为 60 个字符的行,但不要打断单词。所以它不必加起来最多 60 个字符只需少于 60 个即可。

下面的代码是我所拥有的并且可以正常工作,但我认为还有更好的方法。有人吗?

修改为使用StringBuilder,修复了去除重复词的问题。也不想使用正则表达式,因为我认为那会比我现在使用的效率低。

public static List<String> FormatMe(String Message)
{
Int32 MAX_WIDTH = 60;
List<String> Line = new List<String>();
String[] Words;

Message = Message.Trim();
Words = Message.Split(" ".ToCharArray());

StringBuilder s = new StringBuilder();
foreach (String Word in Words)
{
s.Append(Word + " ");
if (s.Length > MAX_WIDTH)
{
s.Replace(Word, "", 0, s.Length - Word.Length);
Line.Add(s.ToString().Trim());
s = new StringBuilder(Word + " ");
}
}

if (s.Length > 0)
Line.Add(s.ToString().Trim());

return Line;
}

谢谢

最佳答案

另一个(现已测试)示例,与 Keith approach 非常相似:

static void Main(string[] args)
{
const Int32 MAX_WIDTH = 60;

int offset = 0;
string text = Regex.Replace(File.ReadAllText("oneline.txt"), @"\s{2,}", " ");
List<string> lines = new List<string>();
while (offset < text.Length)
{
int index = text.LastIndexOf(" ",
Math.Min(text.Length, offset + MAX_WIDTH));
string line = text.Substring(offset,
(index - offset <= 0 ? text.Length : index) - offset );
offset += line.Length + 1;
lines.Add(line);
}
}

我在 this file 上运行了它所有换行符手动替换为“”。

关于c# - 将长字符串分成 60 个字符的长行但不要打断单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1678051/

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