The easiest way to eliminate "non-essential" repeated characters in a string

I have a line similar to "foo-bar ---- baz-biz"

What is the easiest and fastest way to eliminate minor duplicate characters ( - ) and make the string "foo-bar-baz-biz"?

I tried doing something like .Replace("--","-") , but it seems that only a few works. I need to run it in a loop to do this completely, and I know there is a better way.

What is the best way?

+4
source share
3 answers

Try it,

 string finalStr = string.Join("-", x.Split(new[] { '-' }, StringSplitOptions.RemoveEmptyEntries)) 

much better if it converts to Extension method

 static class StringExtensions { public static string RemoveExtraHypen(this string str) { return string.Join("-", str.Split(new []{'-'}, StringSplitOptions.RemoveEmptyEntries)); } } 

Using

 private void SampleDemo() { string x = "foo-bar----baz--biz"; Console.WriteLine(x.RemoveExtraHypen()); } 
+10
source

try Regex class

 using System.Text.RegularExpressions; string input = "foo-bar----baz--biz"; Regex regex = new Regex("\\-+"); string output = regex.Replace(input, "-"); 
+4
source

Very simple solution :)

  private string RemoveDuplicates(string s, char toRemove) { if (s.Length <= 1) return s; char s1,s2; string result=""; result = s[0].ToString(); s1 = s[0]; for (int i = 0; i < s.Length-1; i++) { s2 = s[i + 1]; if ( s2.Equals(toRemove)&& s1.Equals(s2)) { s1 = s[i]; continue; } result += s2.ToString(); s1 = s[i + 1]; } return result; } 

string s = RemoveDuplicates ("f --- oo-bar ---- baz-biz", '-');

0
source

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


All Articles