This document contains C code to find the first non-repeating character in a string. It defines functions to get a character count array from a string and find the first non-repeating character's index. The main function tests it by getting a string from the user and calling firstNonRepeating to get the index, printing the result. It allocates memory for and returns a character count array, loops through the string to count each character, and returns the first index where the count is 1, or -1 if all counts are greater than 1.
This document contains C code to find the first non-repeating character in a string. It defines functions to get a character count array from a string and find the first non-repeating character's index. The main function tests it by getting a string from the user and calling firstNonRepeating to get the index, printing the result. It allocates memory for and returns a character count array, loops through the string to count each character, and returns the first index where the count is 1, or -1 if all counts are greater than 1.
This document contains C code to find the first non-repeating character in a string. It defines functions to get a character count array from a string and find the first non-repeating character's index. The main function tests it by getting a string from the user and calling firstNonRepeating to get the index, printing the result. It allocates memory for and returns a character count array, loops through the string to count each character, and returns the first index where the count is 1, or -1 if all counts are greater than 1.
of characters in the passed char array */ int *getCharCountArray(char *str) { int *count = (int *)calloc(sizeof(int), NO_OF_CHARS); int i; for (i = 0; *(str+i); i++) count[*(str+i)]++; return count; }
/* The function returns index of first non-repeating
character in a string. If all characters are repeating then returns -1 */ int firstNonRepeating(char *str) { int *count = getCharCountArray(str); int index = -1, i;
for (i = 0; *(str+i); i++)
{ if (count[*(str+i)] == 1) { index = i; break; } }
free(count); // To avoid memory leak
return index; }
/* Driver program to test above function */
int main() { clrscr(); char str[80]; int n,i; char t;
printf("enter no of character ");
scanf("%d",&n); printf("enter value "); for(i=0;i<n;i++) { scanf("%c",&t); str[i]=t; } str[i]='\0'; int index = firstNonRepeating(str); if (index == -1) printf("Either all characters are repeating or string is empty"); else printf("First non-repeating character is %c", str[index]); printf("%s",str); getch(); getchar(); //return 0; }