消除字符串中"无关紧要"重复字符的最简单方法

Ear*_*rlz 4 .net c# string

我有一个类似于"foo-bar ---- baz - biz"的字符串

什么是最简单,最快速的方法来消除无关紧要的重复字符(-)并使字符串"foo-bar-baz-biz"?

我尝试过做类似的事情.Replace("--","-"),但这似乎只是有点工作......我必须在循环中运行才能完全完成它,我知道有更好的方法.

什么是最好的方式?

Joh*_*Woo 10

试试这个,

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

如果这转化为更好的话会好得多 Extension method

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

用法

private void SampleDemo()
{
    string x = "foo-bar----baz--biz";
    Console.WriteLine(x.RemoveExtraHypen());
}
Run Code Online (Sandbox Code Playgroud)