Search code examples
c#substringfolddelimited

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


Looking for best solution to create a number of sub-strings such that the length of each sub-string does not exceed the length value in parameter. It should converts spaces to specified separator(let's use comma as an example) when enclosed in sub-strings and removes extraneous spaces. Example:

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

Solution

  • The hard part is handling the spaces, I think. This is what I came up with

      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);
      }
    

    Then you can call it like this

      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));
    

    and the output is

    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.