Izzy
Izzy

Reputation: 6866

Replace all occurrences of a character in a string after the first one

I have a string like

string s = "abc; abc bla bla ;;;;; bla bla";

I want to replace the all but the first ; with a :. I can get the count as follows:

int t = s.Where(e => e.ToString() == ";").Count();

If I do s.Replace(';', ':'); all the ; are replaced with :. Can someone tell me how to achieve this please.

Upvotes: 1

Views: 1156

Answers (1)

Jamiec
Jamiec

Reputation: 136114

With a bit of regex:

string s = "abc; abc bla bla ;;;;; bla bla";
var regex = new Regex("(?<!^[^;]*);");
var result = regex.Replace(s,":");
Console.WriteLine(result);

Live example: http://rextester.com/ORZU81353

Upvotes: 6

Related Questions