打印给定字符串中不重复的第一个字符
Printing the first character in a given string which does not repeat
我在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
的结果是什么,语句都会被求值。
相关文章:
- 如何忽略第一个字符输入后的所有内容
- 增量生成 - 错误:字符串的第一个字符应'0'或'1'
- 对c++中的输入使用getline函数时忽略第一个字符
- C++如何通过忽略每行的第一个字符来读取 unicode 文件
- 输入文件中的第一个字符是输出文件中的最后一个字符,反之亦然
- 检索字符串的第一个字符,并在C++中按字母顺序进行比较
- 这个RLE解码功能只解码第一个字符,我做错了什么?
- 如何忽略除第一个字符之外的所有字符
- C++ 如何从用户输入中读取第一个字符并忽略 rest(字符类型)
- CIN.IGNORE删除第一个字符的第二次函数被调用
- 使用CTYPES将字符串从Python传递到C - 仅发送第一个字符
- 为什么在使用循环时忽略输入的第一个字符
- 仅将输入的第一个字符用于 char 变量
- getline删除第一个字符;删除cin.ignore();无法解决
- 仅分配第一个字符,将 LPCTSTR 转换为字符*
- 如何获取指向字符数组中第一个字符的常量指针
- 访问没有字符的字符串的第一个字符
- 如何将 char 类型数组传递给函数并将第一个字符数组复制到第二个图表数组并使用 c++ 进行比较
- 文本文件中的第一个字符会导致 .substr() 错误
- RegSetValueEx 仅显示写入第一个字符