gpt4 book ai didi

c# - 在 x 个字符上换行一个字符串,但不通过一个单词

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

我会尽力解释我正在寻找的东西。目前,我正在使用此代码每隔 x 个字符换行。

public static string SpliceText(string text, int lineLength)
{
return Regex.Replace(text, "(.{" + lineLength + "})", "$1" + Environment.NewLine);

}

这很好用,但通常它会打断每个 x 数字,显然有时会打断一个单词。代码是否可以检查它是否中断了中间词,如果它不是中间词无论如何都要中断,但现在检查中断后的第一个字符是否是空格,如果是,则将其删除?

我知道我要求很多,但还是先谢谢你了!

最佳答案

试试这个:

public static string SpliceText(string text, int lineLength)
{
var charCount = 0;
var lines = text.Split(new string[] {" "}, StringSplitOptions.RemoveEmptyEntries)
.GroupBy(w => (charCount += w.Length + 1) / lineLength)
.Select(g => string.Join(" ", g));

return String.Join("\n", lines.ToArray());
}

这是我的屏幕截图: enter image description here

关于c# - 在 x 个字符上换行一个字符串,但不通过一个单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16727390/

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