在空格处拆分长串

 政儒思贤丽正 发布于 2023-02-13 10:00

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

private List SliceString(string stringtocut)
{
    List parts = new List();
    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个字符,但如果可以的话,请回到最近的空格?我已经习惯了上面的算法,但我似乎无法得到它.

谢谢!

1 个回答
  • 也许使用这样的正则表达式:

    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." ]
    

    2023-02-13 10:03 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有