将字符串拆分为给定长度的子字符串集,由分隔符分隔

Split string into set of sub-strings with given length, delimited by separator

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

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

我认为最困难的部分是处理空格。这是我想出的

  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.