我的代码有时会起作用。例如,对于字符串" abccba" a不返回0,b不返回1,但c返回3。谁能告诉我我做错了什么?
#define NOT_FOUND (-1) // integer indicator for not found.
/*
* Return the index of the first occurrence of any character in <stop>
* in the given <string>, or (-1) if the <string> contains no character
* in <stop>.
*/
int find_any_index(char string[], char stop[]) {
unsigned int i = 0;
while(stop[i] != '\0'){
if(find_ch_index(string,stop[i])!=NOT_FOUND){
return find_ch_index(string,stop[i]);
}
i++;
}
return NOT_FOUND ; // placeholder
}
/*
* Return the index of the first occurrence of <ch> in <string>,
* or (-1) if the <ch> is not in <string>.
*/
int find_ch_index(char string[], char ch) {
unsigned int i = 0;
while(string[i] != '\0'){
char c = string[i];
if(ch == c){
return i;
}
i++;
}
return NOT_FOUND ; // placeholder
}
答案 0 :(得分:2)
你的逻辑是倒置的。您将在stop
找到的字符串中的第一个字符的目标字符串中返回索引。这不是您的评论所声称的!
E.g。如果停止为ab
且输入为"bba"
,则您的例程将返回2,因为input[2] == stop[0]
。它应该返回0,因为input[0] == stop[1]
。
仔细阅读,仔细思考,然后编码。
答案 1 :(得分:2)
在find_any_index中,您应该替换:
return find_ch_index(string,stop[i]);
使用:
return i;
答案 2 :(得分:0)
感谢大家的帮助。这是我提出的工作解决方案:
/*
* Return the index of the first occurrence of any character in <stop>
* in the given <string>, or (-1) if the <string> contains no character
* in <stop>.
*/
int find_any_index(char string[], char stop[]) {
unsigned int i = 0;
unsigned int j = 65535;
while(stop[i] != '\0'){
if(find_ch_index(string,stop[i])!=NOT_FOUND){
if(j > find_ch_index(string,stop[i])){
j = find_ch_index(string,stop[i]);
}
}
i++;
}
if(j != 65535){
return j;
}
return NOT_FOUND ; // placeholder
}
答案 3 :(得分:0)
或者在一个功能中:
int indexOfAny( char cstrInput[], char cstrSearchCharacters[] )
{
int i = 0;
int inner = 0;
while( 0 != cstrInput[i] )
{
inner = 0;
while( 0 != cstrSearchCharacters[inner] )
{
if ( cstrInput[i] == cstrSearchCharacters[inner] )
{
return i;
}
++inner;
}
++i;
}
return NOT_FOUND;
}
没试过但它应该有用。
我不喜欢你的解决方案,因为它使用幻数(65535)。