Reduce a few consecutive equal characters from a string to one

Basically, I want to take a string, and if there are several "+" in a string, I want to delete all but one. So:

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

will become

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

I'm not sure if LINQ or Regex or anything else works best, but you don’t need to use any specific method.

+5
source share
4 answers
 Regex.Replace(str, @"\++", "+"); 
+10
source

There are ways to do this with less code (and @slaks showed me how much I need to retrain the regex), but it should be as fast as possible in most cases if you do it a lot.

 public static string RemoveDupes(this string replaceString, char dupeChar){ if(replaceString == null || String.Length < 2){ return replaceString; } int startOfGood = 0; StringBuilder result = new StringBuilder(); for(int x = 0;x<replaceString.Length-1;x++){ if(replaceString[x] == dupeChar && replaceString[x+1] == dupeChar){ result.Append(replaceString.SubString(startOfGood,x-startOfGood));//I think this works with length 0 startOfGood = x+1; } } result.Append(replaceString.Substring(startOfGood, replaceString.Length-startOfGood)); return result.ToString(); } //Usage: var noDupes = "This++is+an++++ex+ampl++e".RemoveDupes('+'); 
0
source

Microsoft Interactive Extensions (Ix) has a DistinctUntilChanged method that does what you want. This library comes with many useful features, but it is another whole library that you might not want to worry about.

Usage will look like this:

 str = new string(str .ToEnumerable() .DistinctUntilChanged() .ToArray()); 

If you want to remove only plus signs, you can do this:

 str = new string(str .ToEnumerable() .Select((c, i) => new { c, i = (c != '+' ? i : -1) }) .DistinctUntilChanged() .Select(t => tc) .ToArray()); 
0
source
 while (str.Contains("++")) str = str.Replace("++", "+"); 
0
source

Source: https://habr.com/ru/post/1480590/


All Articles