c# - 在空格处拆分长字符串

标签 c# .net string

在我的程序中,如果字符串太长,我需要将它分成多行。现在我正在使用这种方法:

private List<string> SliceString(string stringtocut)
{
    List<string> parts = new List<string>();
    int i = 0;
    do
    {  
        parts.Add(stringtocut.Substring(i, System.Math.Min(18, stringtocut.Substring(i).Length)));
        i += 18;
    } while (i < stringtocut.Length);
    return parts;
}

唯一的问题是,如果第 19 个字符不是空格,我们将一个单词切成两半,看起来很糟糕。

例如

字符串: 这是一个超过 18 个字母的长句子。

Sliced string: 
This is a long sent
ance with more than
 18 letters.

我如何剪切字符串以使其每节不超过 18 个字符,但如果可以的话返回到最近的空格?我一直在玩弄上面的算法,但我似乎无法理解。

谢谢!

最佳答案

也许使用这样的正则表达式:

var input = "This is a long sentence with more than 18 letters.";
var output = Regex.Split(input, @"(.{1,18})(?:\s|$)")
                  .Where(x => x.Length > 0)
                  .ToList();

返回结果:

[ "This is a long", "sentence with more", "than 18 letters." ]

更新

这里有一个处理超长单词的类似解决方案(尽管我感觉它的性能不会那么好,因此您可能需要对其进行基准测试):

var input = "This is a long sentence with a reallyreallyreallyreallyreallyreallyreallyreallyreallyreallyreallyreallyreally long word in it.";
var output = Regex.Split(input, @"(.{1,18})(?:\s|$)|(.{18})")
                  .Where(x => x.Length > 0)
                  .ToList();

这会产生结果:

[ "This is a long", 
  "sentence with a", 
  "reallyreallyreally", 
  "reallyreallyreally", 
  "reallyreallyreally", 
  "reallyreallyreally", 
  "really long word", 
  "in it." ]

关于c# - 在空格处拆分长字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20360497/

相关文章:

.net - HttpClient GetAsync 处置 Webjob 处理程序

arrays - 日期转换程序中的奇怪错误

c++ - 初始化字符串 vector 数组时出错

c# - Json 反序列化未知或通用模型类型

c# - 在 Starcounter 中启用 CORS

c# - 查找数组中项目的所有组合的最佳方法是什么?

c# - 依赖于字符串值的业务逻辑

c# - Roslyn c# CSharpCompilation - 编译动态

c# - 创建单实例 WPF 应用程序的正确方法是什么?

c++ - 给定条件下长度 N 个数内的所有可能序列