Find First Non Repeating Character Using C#

Hello all, today I will explain how can we find the first non-repeating character from a string using C# code. So let’s start. Check the below code.

Code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FirstNonRepeattingChar
{
    class Program
    {
        static void Main(string[] args)
        {
            FindNonRepeattingChar("Chand Dakhara");
            Console.ReadKey();
        }
        public static void FindNonRepeattingChar(string str)
        {
            try
            {
                for (int i = 0; i < str.Length; i++)
                {
                    if (str.IndexOf(str[i], str.IndexOf(str[i]) + 1) == -1)
                    {
                        Console.WriteLine("Non Repeated Character Is : " + str[i]);
                        break;
                    }
                }
            }
            catch (Exception ex)
            {

                Console.WriteLine(ex.ToString());
            }
        }
    }
}

This C# function FindNonRepeattingChar takes a string str as input and tries to find the first non-repeating character in the string. The function uses a for-loop to iterate over all characters in the input string. For each character, it uses the IndexOf method to find the index of the first occurrence of that character in the string. It then uses IndexOf again, but this time with an additional parameter to start the search after the first occurrence of the character. If the result of this second IndexOf call is -1, it means that the character only occurred once in the string, and the function prints a message indicating that it found the first non-repeating character.

Output:

 

Submit a Comment

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

Subscribe

Select Categories