Corrected code:
int strrindex(char *s, char *t) {
int i, j, k, p;
i = -1;
for (k = 0; s[k] != '\0'; k++) {
if (strlen(s) < strlen(t)) break;
if (s[k] == t[0]) {
for (p = k; s[p] != '\0'; p++) {
j = p;
while (s[j] != '\0' && s[j] == t[j-k] && t[j-k] != '\0') { j++; }
if (t[j-k] != '\0') { break; }
i = k;
}
}
}
printf("%d\n", i);
return 0;
}
for (p = k; s[p] != '\0'; p++) {
while (s[p] == t[p] && t[p] != '\0') { p++; }
At this point, you are comparing string s
starting at position p
with string t
starting at position 0. So it shouldn't be t[p]
, but instead t[p - k]
.
if (s[p] != t[p] || t[p] != '\0') { i = -1; }
You don't need this at all - if the current section doesn't match, you just leave i
at the last match. (which will anyway be -1 if there has been no match so far)
I think this should work:
int strrindex(char *s, char *t) {
int i = -1;
int j = 0;
int k = 0;
for (; s[k]; k++) {
if(!t[j]) {
i = k - j;
j = 0;
}
if (s[k] != t[j])
j = 0;
else
j++;
}
if(!t[j + 1])
i = k - j - 1;
return i;
}
p
is indexing both s[p]
and t[p]
. That's incorrect, since they're both different indices. if (s[p] != t[p] ...) i = -1;
has no effect, because you then immediately set it to k
. You're not the first person to want such a function.
See: Is there a reverse fn() for strstr? for some example implementations.
There are several bugs in your code. Here are the ones I've found:
There's a great reference on substring search algorithms here: http://www-igm.univ-mlv.fr/~lecroq/string/index.html
With any of them, you can simply switch things around to start with pointers to the last byte of the string and negate the indices.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.