Мне нужно написать код для задания, которое находит подстроку внутри строки.Поиск подстроки
Вот мой код, и я добавил комментарии:
// 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"
.
Поскольку это в основном просто 'strstr()', я предлагаю вам взглянуть на реализацию, e. г. один в glibc. –
Изменить этот код? или хочет лучше? –