首页 > 解决方案 > 将字符串拆分为具有给定长度的子字符串集,由分隔符分隔

问题描述

寻找创建多个子字符串的最佳解决方案,以使每个子字符串的长度不超过参数中的长度值。当包含在子字符串中时,它应该将空格转换为指定的分隔符(让我们以逗号为例)并删除无关的空格。例子:

input string = "Smoking is one of the leading causes of statistics"

length of substring = 7

result = "Smoking,is one,of the,leading,causes,of,statist,ics."

input string = "Let this be a reminder to you all that this organization will not tolerate failure."

length of substring = 30

result = "let this be a reminder to you,all that this organization_will not tolerate failure."

标签: c#substringfolddelimited

解决方案


我认为,困难的部分是处理空间。这就是我想出的

  private string SplitString(string s, int maxLength)
  {
    string rest = s + " ";
    List<string> parts = new List<string>();
    while (rest != "")
    {
      var part = rest.Substring(0, Math.Min(maxLength, rest.Length));
      var startOfNextString = Math.Min(maxLength, rest.Length);
      var lastSpace = part.LastIndexOf(" ");
      if (lastSpace != -1)
      {
        part = rest.Substring(0, lastSpace);
        startOfNextString = lastSpace;
      }
      parts.Add(part);
      rest = rest.Substring(startOfNextString).TrimStart(new Char[] {' '});
    }

    return String.Join(",", parts);
  }

然后你可以这样称呼它

  Console.WriteLine(SplitString("Smoking is one of the leading causes of statistics", 7));
  Console.WriteLine(SplitString("Let this be a reminder to you all that this organization will not tolerate failure.", 30));

输出是

Smoking,is one,of the,leading,causes,of,statist,ics
Let this be a reminder to you,all that this organization,will not tolerate failure.

推荐阅读