Earlz
Earlz

Reputation: 63835

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

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?

Upvotes: 4

Views: 298

Answers (3)

Sathish Raja
Sathish Raja

Reputation: 131

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", '-');

Upvotes: 0

John Woo
John Woo

Reputation: 263723

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());
}

Upvotes: 10

Rick Su
Rick Su

Reputation: 16440

try Regex class

using System.Text.RegularExpressions;

string input = "foo-bar----baz--biz";

Regex regex = new Regex("\\-+");

string output = regex.Replace(input, "-");

Upvotes: 4

Related Questions