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.

C# Program
using System;
using System.Linq;
 class Program
    {
        static void Main()
        {
            string value1 = RemoveDuplicateChars("DotneTOffice");
            string value5 = RemoveDuplicate("Line1\nLine2\nLine3");

            Console.WriteLine(value1);
            Console.WriteLine(value5);
            Console.ReadLine();
        }

        static string RemoveDuplicateChars(string input)
        {
           
            input = input.ToUpper();
            string TempResult = "";        
            string result = "";
      
            foreach (char value in input)
            {
                // See if character is in the table.
                if (TempResult.IndexOf(value) == -1)
                {
                    // Append to the table and the result.
                    TempResult += value;
                    result += value;
                }
            }
            return result;
        }

     // Another method to remove duplicate char
        static string RemoveDuplicate(string input)
        {
            input = input.ToUpper();
            string DistinctString = new string(input.Distinct().ToArray());
            return DistinctString;
        }
    }


Share this

Related Posts

Previous
Next Post »