Introduction
In this blog, we will study how we can find the first repeated character in a string.
Given below code snippet will help you to understand how we will find first repeated character in a string.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CSharpAdvanncedProgramming
{
public static class FirstRepeating
{
public static char FirstRepeatingChar(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';
}
}
}
Main Class Code
using CSharpAdvanncedProgramming;
string Input = "Mudassar Ali";
Char[] chars = Input.ToCharArray();
char res = FirstRepeating.FirstRepeatingChar(chars);
Console.WriteLine("First Repeated Char In String Is :"+res);
Program Output