Find the first un-repeated character in a string

后端 未结 30 1276
猫巷女王i
猫巷女王i 2020-11-27 18:29

What is the quickest way to find the first character which only appears once in a string?

30条回答
  •  [愿得一人]
    2020-11-27 19:06

    Different approach here. scan each element in the string and create a count array which stores the repetition count of each element. Next time again start from first element in the array and print the first occurrence of element with count = 1

    C code 
    -----
    #include 
    #include 
    
    int main(int argc, char *argv[])
    {
        char t_c;
        char *t_p = argv[1] ;
        char count[128]={'\0'};
        char ch;
    
        for(t_c = *(argv[1]); t_c != '\0'; t_c = *(++t_p))
            count[t_c]++;
        t_p = argv[1];
        for(t_c = *t_p; t_c != '\0'; t_c = *(++t_p))
        {
            if(count[t_c] == 1)
            {
                printf("Element is %c\n",t_c);
                break;
            }
        }
    
    return 0;    
    } 
    

提交回复
热议问题