我想找到字符串中最后一次出现的字符串(不是 NULL 终止的)。 搜索到的子字符串总是 4 个字母长。这是我尝试过的:
char * strrstr(char *string, char *find, ssize_t len)
{
//I see the find in string when i print it
printf("%s", string);
char *cp;
for (cp = string + len - 4; cp >= string; cp--)
{
if (strncmp(cp, find, 4) == 0)
return cp;
}
return NULL;
}
尽管我看到了我在字符串参数中寻找的子字符串,但它总是给我 NULL。
最佳答案
我用这种方式试过你的代码,它成功运行
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
char * strrstr(char *string, char *find, ssize_t len)
{
//I see the find in string when i print it
//printf("%s", string);
char *cp;
for (cp = string + len - 4; cp >= string; cp--)
{
if (strncmp(cp, find, 4) == 0)
return cp;
}
return NULL;
}
int main() {
char *ret = strrstr("kallelkallelkallelkallaa", "kall", 23);
printf("%s", ret); //---> it prints: kallaa
return 0;
}
关于c - 查找最后一次出现的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20213799/