Write an efficient function to find the first non-repeated character in a string. For example, the first non-repeated character in "total" is 'o' and the first non-repeated character in "teeter" is 'r'.
Please see my solution and give me some feedback and suggestions for improving and optimizing it if needed.
#include <stdio.h>
#define SIZE 100 /* max size of input string */
#define LIM 5 /* max number of inputs */
char repeat_ch(const char *); /* return first non-repeated character */
int main(void)
{
char line[SIZE];
int i = 0;
char ch;
while(i < LIM && gets(line))
{
ch = repeat_ch(line);
if(ch != NULL)
printf("1st non-repeated character: %c\n", ch);
else
printf("There is no unique character in a string: %s\n", line);
i++;
}
}
char repeat_ch(const char *string)
{
char array[130] = {0};
char *p = string;
/* store each character in array, use ascii code as an index for character
* increment each time the same character appears in a string
*/
while(*p) // stop when '\0' encountered
{
array[*p]+=1;
p++;
}
while(*string)
{
if(array[*string] == 1)
return *string; // stop when unique character found
string++;
}
return *string;
}