Find The First Repeated Character From String In C#

In this article, I will explain how we can find the first repeated character from a string. Check the below code. I have created one console application to do it.

Code

using System;
using System.Collections.Generic;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            string CharStr = "Hello All, This is Chand Dakhara.";
            Char[] chars = CharStr.ToCharArray();
            char result = FindFirstRepeatingChar(chars);
            Console.WriteLine("Your String IS :: " + CharStr);
            Console.WriteLine("First Repeated Char In String Is :: " + result);
            Console.ReadKey();
        }
        public static char FindFirstRepeatingChar(char[] chars)
        {
            HashSet<char> result = new HashSet<char>();
            for (int i = 0; i < chars.Length; i++)
            {
                char c = chars[i];
                if (result.Contains(c))
                {
                    return c;
                }
                else
                {
                    result.Add(c);
                }
            }
            return '\0';
        }
    }
}

Output

 

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories