Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

110
Views
How to split string after every n-th character?

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!

over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

You could also use a pattern to match 1 or more characters except for a comma using a negated character class [^,]+ before and after the comma:

string pattern = @"[^,]+,[^,]+";
string input = "This,is,an, example,for,the,stackoverflow,community";
foreach (Match m in Regex.Matches(input, pattern))
{
    Console.WriteLine(m.Value);
}

Output

This,is
an, example
for,the
stackoverflow,community
over 4 years ago · Santiago Trujillo Report

0

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.

over 4 years ago · Santiago Trujillo Report

0

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:

  • how do I chunk an enumerable?
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!