Viveka
Viveka

Reputation: 370

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

I have a string say

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

and I want to split it on the 2nd last occurrence of a comma in C# i.e

a = "xy,yz,zx,ab"
b = "bc,cd"

How can I achieve this result?

Upvotes: 0

Views: 408

Answers (4)

Enigmativity
Enigmativity

Reputation: 117124

It you get Microsoft's System.Interactive extensions from NuGet then you can do this:

string output = String.Join(",", str.Split(',').TakeLast(2));

Upvotes: 0

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186803

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

Upvotes: 2

Fabio
Fabio

Reputation: 32455

Alternative "readable" approach ;)

const string text = "xy,yz,zx,ab,bc,cd";

var words = text.Split(',');
var firstBatch = Math.Max(words.Length - 2, 0);

var first = string.Join(",", words.Take(firstBatch));
var second = string.Join(",", words.Skip(firstBatch));

first.Should().Be("xy,yz,zx,ab"); // Pass OK
second.Should().Be("bc,cd");      // Pass OK

Upvotes: 1

Tim Biegeleisen
Tim Biegeleisen

Reputation: 521914

You could handle this via regex replacement:

var str = "xy,yz,zx,ab,bc,cd";
var a = Regex.Replace(str, @",[^,]+,[^,]+$", "");
var b = Regex.Replace(str, @"^.*,([^,]+,[^,]+)$", "$1");
Console.WriteLine(a);
Console.WriteLine(b);

This prints:

xy,yz,zx,ab
bc,cd

Upvotes: 0

Related Questions