在空格处拆分长串

Nat*_*han 5 .net c# 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;
}
Run Code Online (Sandbox Code Playgroud)

唯一的问题是,如果第19个字符不是空格,我们会将一个字缩小一半,看起来非常糟糕.

例如

字符串:这是一个超过18个字母的长信号.

Sliced string: 
This is a long sent
ance with more than
 18 letters.
Run Code Online (Sandbox Code Playgroud)

我如何剪切字符串,使其每个部分不超过18个字符,但如果可以的话,请回到最近的空格?我已经习惯了上面的算法,但我似乎无法得到它.

谢谢!

p.s*_*w.g 15

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

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();
Run Code Online (Sandbox Code Playgroud)

返回结果:

[ "This is a long", "sentence with more", "than 18 letters." ]
Run Code Online (Sandbox Code Playgroud)

更新

这是一个类似的解决方案来处理很长的单词(虽然我觉得它不会表现得那么好,所以你可能想要对此进行基准测试):

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();
Run Code Online (Sandbox Code Playgroud)

这会产生结果:

[ "This is a long", 
  "sentence with a", 
  "reallyreallyreally", 
  "reallyreallyreally", 
  "reallyreallyreally", 
  "reallyreallyreally", 
  "really long word", 
  "in it." ]
Run Code Online (Sandbox Code Playgroud)

  • @pswg:我知道了.在空间上分裂,最多18个,但是如果没有找到空格就是"@"(?:(.{1,18})(?:\ s | $)|(.+?)(?:\ s | $ ))"`.空间上的分裂,最多18个,但如果没有找到空格,则分裂为18,"@ :(.{1,18})(?:\ s | $)|(.{18}))"`.感谢您展示这种有趣的方法. (3认同)