Skip to main content

C# extension method that trims or removes duplicate delimited characters and leave only one instance of that character. If you like to have a comma delimited value and you like to remove excess commas, this extension method is for you. Other characters are supported too, this includes pipe and colon.

// ----------------------------------------------------------------------------
// Trim Duplicates from String
//
// Trims or removes duplicate delimited characters and leave only one instance
// of that character. If you like to have a comma delimited value and you like
// to remove excess commas, this extension method is for you. Other characters
// are supported too, this includes pipe and colon.
// ----------------------------------------------------------------------------

static class Strings
{
    public enum TrimType
    {
        Comma,
        Pipe,
        Colon
    }

    public static string TrimDuplicates(this string input, TrimType trimType)
    {
        string result = string.Empty;

        switch (trimType)
        {
            case TrimType.Comma:
                result = input.TrimCharacter(',');
                break;
            case TrimType.Pipe:
                result = input.TrimCharacter('|');
                break;
            case TrimType.Colon:
                result = input.TrimCharacter(':');
                break;
            default:
                break;
        }

        return result;
    }

    private static string TrimCharacter(this string input, char character)
    {
        string result = string.Empty;

        result = string.Join(character.ToString(), input.Split(character)
                             .Where(str => str != string.Empty)
                             .ToArray());

        return result;
    }
}

// ----------------------------------------------------------------------------
// Example Usage:
// ----------------------------------------------------------------------------

static void Main(string[] args)
{
    string input = string.Empty;

    Console.WriteLine("Clean Commas");
    input = "justin,tesla,,nine,,,,,,elevate,,,joel";
    Console.WriteLine("INPUT: {0}\nOUTPUT: {1}\n", input, input.TrimDuplicates(Strings.TrimType.Comma));

    // OUTPUTS: justin,tesla,nine,elevate,joel

    Console.WriteLine("Clean Pipe");
    input = "justin|tesla||nine||||||elevate|||joel";
    Console.WriteLine("INPUT: {0}\nOUTPUT: {1}\n", input, input.TrimDuplicates(Strings.TrimType.Pipe));

    // OUTPUTS: justin|tesla|nine|elevate|joel

    Console.WriteLine("Clean Colon");
    input = "justin:tesla::nine::::::elevate:::joel";
    Console.WriteLine("INPUT: {0}\nOUTPUT: {1}\n", input, input.TrimDuplicates(Strings.TrimType.Colon));

    // OUTPUTS: justin:tesla:nine:elevate:joel

    Console.ReadLine();
}