Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reduce multiple consecutive equal characters from a string to just one

Basically, I want to take a string, and if there are multiple '+'s in a row, i want to remove all but one. So:

"This++is+an++++ex+ampl++e"

would become

"This+is+an+ex+ampl+e"

I'm not sure whether LINQ or Regex or something else would be best suited, but it doesn't have to use any particular method.

like image 978
Wilson Avatar asked May 13 '13 21:05

Wilson


Video Answer


2 Answers

Regex.Replace(str, @"\++", "+");
like image 96
SLaks Avatar answered Sep 21 '22 01:09

SLaks


while (str.Contains("++"))
    str = str.Replace("++", "+");
like image 36
James Carter Avatar answered Sep 20 '22 01:09

James Carter