How to return the first unique character without using inbuilt functions using C#?


Create an empty new array of length 256, traverse through the entire string character by character and increment the value in the new array. At the end traverse the entire array and return the first character that has value 1.

Example 1

aabccd -→2 1 2 1 → Return the first character which is having count 1. That is b by subtracting with the ascii values.

Example 2

 Live Demo

using System;
namespace ConsoleApplication{
   public class Arrays{
      public char ReturnCharacterOfFirstUniqueCharachter(string s){
         int index = -1;
         int[] arrayValues = new int[256];
         for (int i = 0; i < s.Length; i++){
            int value = s[i] - 'a';
            arrayValues[value] += 1;
         }
         for (int i = 0; i < s.Length; i++){
            int value = s[i] - 'a';
            if (arrayValues[value] == 1){
               index = i;
               break;
            }
         }
         return s[index];
      }
   }
   class Program{
      static void Main(string[] args){
         Arrays a = new Arrays();
         Console.WriteLine(a.ReturnCharacterOfFirstUniqueCharachter("bbookisgreat"));
         Console.ReadLine();
      }
   }
}

Output

k

Updated on: 27-Aug-2021

134 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements