Program to Remove Duplicate characters from String in C#

The string may have two or more same characters in it but we want it to have only one. So let’s look at an example to understand it better.


Required input and output

Input: Csharpstar Output: Csharpt


Input: Google Output: Gogle


Input: Yahoo Output: Yaho


Input: CNN Output: CN


Simple way of Implementation:

The essential logic in removing duplicate characters is to check all the chars that have been encountered and avoid adding further characters that have been encountered already.


 class Program
    {
        static void Main()
        {
            string value1 = RemoveDuplicateChars("Csharpstar");
            string value2 = RemoveDuplicateChars("Google");
            string value3 = RemoveDuplicateChars("Yahoo");
            string value4 = RemoveDuplicateChars("CNN");
            string value5 = RemoveDuplicateChars("Line1\nLine2\nLine3");

            Console.WriteLine(value1);
            Console.WriteLine(value2);
            Console.WriteLine(value3);
            Console.WriteLine(value4);
            Console.WriteLine(value5);
        }

        static string RemoveDuplicateChars(string key)
        {
            // --- Removes duplicate chars using string concats. ---
            // Store encountered letters in this string.
            string table = "";

            // Store the result in this string.
            string result = "";

            // Loop over each character.
            foreach (char value in key)
            {
                // See if character is in the table.
                if (table.IndexOf(value) == -1)
                {
                    // Append to the table and the result.
                    table += value;
                    result += value;
                }
            }
            return result;
        }
    }



Output:






Source: csharpstar


The Tech Platform

www.thetechplatform.com

0 comments