C# String splitting - breaking string up at second comma

You can use a regular expression to match two items in the string:

string[] parts =
  Regex.Matches(myarray[0], "([^,]*,[^,]*)(?:, |$)")
  .Cast<Match>()
  .Select(m => m.Groups[1].Value)
  .ToArray();

This gets the items from the first string in the array. I don't know why you have the string in an array and if you have more than one string, in that case you have to loop through them and get the items from each string.


There is no direct way to make String.Split do this.

If performance is not a concern, you can use LINQ:

var input = "test1, 1, anotherstring, 5, yetanother, 400";

string[] result = input.Split(',');
result = result.Where((s, i) => i % 2 == 0)
               .Zip(result.Where((s, i) => i % 2 == 1), (a, b) => a + ", " + b)
               .ToArray();

Otherwise you'll probably have to split the string manually using String.IndexOf, or using a regular expression.


Another LINQ-based solution here. (Perhaps not the most efficient, but it allows for concise code and works for grouping into arbitrary group sizes).


1) Define a new query operator, InGroupsOf:

public static IEnumerable<T[]> InGroupsOf<T>(this IEnumerable<T> parts,
                                             int groupSize)
{
    IEnumerable<T> partsLeft = parts;
    while (partsLeft.Count() >= groupSize)
    {
        yield return partsLeft.Take(groupSize).ToArray<T>();
        partsLeft = partsLeft.Skip(groupSize);
    }
}

2) Second, apply it to your input:

// define your input string:
string input = "test1, 1, anotherstring, 5, yetanother, 400";

// split it, remove excessive whitespace from all parts, and group them together:
IEnumerable<string[]> pairedInput = input
                                    .Split(',')
                                    .Select(part => part.Trim())
                                    .InGroupsOf(2);  // <-- used here!

// see if it worked:
foreach (string[] pair in pairedInput)
{
    Console.WriteLine(string.Join(", ", pair));
}

Tags:

C#

String

Split