C program to find first non-repeating character in a string

Non-repeating character in a string

If a string has a non repeating character then, that character should be the output. If there are two or more non-repeating characters then the first non-repeating character should be the output.It is explained clearly in the example given below.
Example: 
        If the given string is  InterviewCodingPrep then the output should be 't' because t is the 1st non repeating character in the string

INPUT: InterviewCodingPrep

OUTPUT: t

Program:

#include<stdlib.h>
#include<stdio.h>
#define NUM 300  // NUM is constant here

int *getCount(char *s)    
{
   //method to count the number of characters
int *count = (int *)calloc(sizeof(int), NUM);
int i;
for (i = 0; *(s+i); i++)
count[*(s+i)]++;
return count;
}
int nonRepeat(char *s) 
{  
   //method to find the first non-repeating character
int *count = getCount(s);
int index = -1, i;
for (i = 0; *(s+i); i++)
 {
  if (count[*(s+i)] == 1)
   {
    index = i;
    break;  //comes out of loop
   }
 }
free(count);
return index;
}

int main()
{
clrscr();   //will clear the screen
char s[NUM];
printf(''\nEnter the string : ");
scanf("%s'', &s);
int index = nonRepeat(s);
if (index == -1)
printf("\nAll the characters in the string are repeated\n");
else
printf("The first non-repeating character in the string is:  %c", s[index]);
getchar();
return 0;
}

OUTPUT:

Enter the string: InterviewCodingPrep
The first non-repeating character in the string is: t

Program explanation:

We include header files stdlib and stdio in the program. 'define' is used to keep a value constant, in general it is recommended to keep constant variables in capital letters. A method getCount(char*s) is created to know the count of the string that is to find number of characters in the given string. s will receive the given string (input string).A method nonRepeat(char*s) is created to know the non repeating characters in the given string and store the first non repeating character. clrscr() is used to clear the screen. printf() will display or print the given text / value on the display screen. scanf() is used to take the input. nonRepeat(s) is an calling method it will call the method. return(0) will return the value to main() function.



No comments:

Post a Comment