Split a String on 2nd last occurrence of comma in C#

Let’s find the required comma index with a help of LastIndexOf:

  var str = "xy,yz,zx,ab,bc,cd";

  // index of the 2nd last occurrence of ','
  int index = str.LastIndexOf(',', str.LastIndexOf(',') - 1);

Then use Substring:

  string a = str.Substring(0, index);
  string b = str.Substring(index + 1); 

Let’s have a look:

  Console.WriteLine(a);
  Comsole.WriteLine(b);

Outcome:

  xy,yz,zx,ab
  bc,cd

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top