我是初学程序员,请原谅我,如果这段代码没有多大意义。我创建了一个函数,试图在字符串(原始)中找到第一次出现的子字符串(toFind)。问题是我有算法,但我不是100%确定如何实现代码。它编译但它不起作用或返回任何东西。帮助我的错误将不胜感激。
int findSubstring(char original[], char toFind[]){
int i = 0;
int j = 0;
int k = 0;
bool flag = false;
for (i=0; i<strlen(toFind); ++i){
for (j=0; j<strlen(original); ++j){
if (toFind[i] == original[j]){
flag = true; //set a flag to indicate a potential match
j = toFind[i]; //set the potential substring position to j
for (k = 1; k<strlen(toFind); ++k){ //for (k) the remaining characters in substring
if (toFind[i+k] == original[j+k]){ //compare toFind[i+k] to original[j+k]
++j;//if they are the same move to next character
flag = true;
}
else{ //if they are different change the matching flag to false
flag = false;
}
}
}
}
}
if (flag == true){
return j;
}
else{
return -1;
}
}
原始示例=“你好吗”
toFind的例子=“是”
应该返回4
编辑:开始认为它与j = toFind [i]
有关