Home > Enterprise >  How to split string after every n-th character?
How to split string after every n-th character?

Time:03-07

I have a string and I want to split the string after every 2nd comma. Is this doable using split string in c#?

Example string:

"This,is,an, example,for,the,stackoverflow,community"

Desired output

This,is
an,example
for,the
stackoverflow,community

Any help would be much appreciated thanks!

CodePudding user response:

Using Enumerable.Chunk from .NET 6, you can

  • split on ",",
  • create chunks of two items each and
  • re-join those chunks:
string input = "This,is,an,example,for,the,stackoverflow,community";

var output = input.Split(",")
    .Chunk(2)
    .Select(chunk => string.Join(",", chunk));

foreach (string s in output)
    Console.WriteLine(s);

fiddle

If you're stuck with the "classic" .NET Framework, here are chunk implementations for .NET < 6:

CodePudding user response:

You could do something like this:

var s = "This,is,an, example,for, the, stackoverflow, community";

var a = (","   s   ",").Split(',');

//  requires using System.Linq;
var b = Enumerable.Range(0, a.Length / 2)
        .Select(i => $"{a[2 * i]}, {a[2 * i   1]}".Trim(',', ' '));

Range enumerates the resulting array and computes concatenations of the corresponding pairs of strings.

  • Related