【问题标题】:Split string into set of sub-strings with given length, delimited by separator将字符串拆分为具有给定长度的子字符串集,由分隔符分隔
【发布时间】:2023-03-11 23:17:01
【问题描述】:

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

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# substring fold delimited


【解决方案1】:

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

  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.

【讨论】:

  • 没错,我遇到了空格问题。感谢您的建议!
猜你喜欢
  • 2017-06-27
  • 2015-12-28
  • 2022-11-17
  • 2014-06-29
  • 1970-01-01
  • 2015-02-13
  • 1970-01-01
  • 2010-10-19
  • 1970-01-01
相关资源
最近更新 更多