Search code examples
.net-2.0

Split comma delimited string into smaller ones


How would I split a comma delimited string into smaller comma delimited strings?

My string looks like this: 1,2,3,4,5,6,7,8,9,10

And I need to split the string after every nth occurrence of the , character.
E.g. for every 3rd occurrence, the above string would be turned into these strings:
1,2,3,4 5,6,7,8 9,10

Might look like homework but it's not, my brain is just tired but I still need to get work done.


Solution

  • Try a loop in which you count the commas ;-)

    Untested, it could look like:

    int lastSplit = 0;
    int commaCount = 0;
    int n = 4;
    List<string> parts = new List<string>();
    
    for (int i = 0; i < s.Length; i++)
    {
       if (s[i] == ',' && ++commaCount == n)
       {
          commaCount = 0;
          parts.Add(s.Substring(lastSplit, i - lastSplit));
          lastSplit = i + 1;
       }
    }
    
    parts.Add(s.Substring(lastSplit));