Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Easiest way to eliminate "insignificant" duplicate characters in a string

Tags:

string

c#

.net

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

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

I've tried doing something like .Replace("--","-"), but that appears to only work somewhat.. I'd have to run it in a loop to do it fully, and I know there is a better way.

What's the best way?

like image 725
Earlz Avatar asked Dec 09 '22 20:12

Earlz


1 Answers

Try this,

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

much better if this is transformed into Extension method

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

usage

private void SampleDemo()
{
    string x = "foo-bar----baz--biz";
    Console.WriteLine(x.RemoveExtraHypen());
}
like image 137
John Woo Avatar answered Dec 11 '22 09:12

John Woo