打印给定字符串中不重复的第一个字符

Printing the first character in a given string which does not repeat

本文关键字:第一个 字符 字符串 打印      更新时间:2023-10-16

我在c++中使用以下函数返回给定字符串中不重复的第一个字符,如果没有找到返回'@'。

char MyMethod(const char* str, int len){
    int i,index=-1;
    int *count = new int[256];
    for(i=0;i<len;i++)
    {
       count[*(str+i)]=0;
    }
    for(i=0;i<len;i++)
    {
       count[*(str+i)]++;
    }
    for(i=0;i<len;i++)
    {
        if(count[*(str+i)]==1)
        {
            index=i;
            break;
        }
    }
    if(index==-1)
        return '@';
    else
        return *(str+index);
}

这个方法看起来很好,但它总是返回字符串的第一个字符。例如,对于下面的字符串

aabcdd

它返回'a'而不是'b'。

我想是打错了。语句:

 if(count[*(str+i)]==1);

不应该被终止:

 if(count[*(str+i)]==1)

去掉分号,这样if条件之后的语句只在条件为真时才计算。否则,无论if的结果是什么,语句都会被求值。