我必须为在字符串中找到子字符串的赋值编写一些代码。
这是我的代码,我添加了注释:
// the target is the substring that we want to find in the source string
// m is the length of the target, and n is the length of the source
int contains(char target[], int m, char source[], int n) {
int flag = 0; // the source originally does not contain the target
int i;
// go through each character of the source string
for(i = 0; i < n; i++) {
int targetIndex = 0;
int j;
// check if the preceding characters of the source string are a substring
// that matches the target string
for(j = i; j < n && targetIndex < m; j++) {
if(target[targetIndex] == source[j]) {
flag = 1;
targetIndex += 1;
}
else {
flag = 0; // a letter does not match
break;
}
}
}
return flag;
}
所以当我测试这个方法时,我总是被0
退回,我不明白为什么。
如果我尝试int i = contains("potatoes", 8, "toes", 4);
它会给0
.
我试过放一些打印语句来查看它匹配的字符,它似乎只找到第一个字母"t"
。