在C中查找字符串的最后一次出现

时间:2017-06-14 08:19:09

标签: c string

我想比较另一个字符串中的字符串,例如“motherfathersister”中的“ther”,结果将为null(不匹配)或最后一次出现后的剩余字符(在此示例中为“thersister”)。 我已经从string.h更改了strstr的实现,但结果是每次都相同。 我犯了哪个错误? 感谢

char *stRstr(char *s, char *m)
{
    char *last=NULL;
    size_t n = strlen(m);
    while(*s)
    {
        if(!memcmp(s++,m,n))
        {
            last=s-1;
        }
    }
    return last;
}

3 个答案:

答案 0 :(得分:0)

谢谢你们 我发现了自己的错误...... 我没有调用我的函数“stRstr”但是“strstr”...而且这个函数已经实现了...... 感谢您的帮助,没有您的反馈,就我的功能返回正确的结果而言,我会失去...

答案 1 :(得分:0)

如评论中所述,您的代码将超出其范围访问s(考虑当s指向最后一个非' \ 0' -character时memcmp的作用)。所以我摆脱了memcmp - 用法,我会从后面扫描字符串。

strstr类似,它快速扫描字符串以查找单字符匹配并比较其余字符,请参阅以下代码,这些代码以向后的方式完全相同。

希望它有所帮助。

const char *stRstr(const char *s, const char *m)
{
    const char* ptr = s + strlen(s);
    size_t mlen = strlen(m);
    while (ptr-- != s) {  // until ptr reaches the beginning of s
        if (*ptr==*m) {   // single character match (first characters of s and m)?
            if (strncmp(ptr,m,mlen)==0)  // check the remainder
                return ptr;
        }
    }
    return NULL;
}

void printLast(const char* s) {
    if (s)
        printf("last: %s\n", s);
    else
        printf("string not found.\n");
}
int main() {

    const char* s = "this is the first, this is the last";
    const char* m = "this";

    const char* last = stRstr(s, m);
    printLast(last);

    last = stRstr(s, "not contained");
    printLast(last);

}

答案 2 :(得分:0)

你的功能应该有效(问题出在其他地方),但它有一些问题:

  • 使用memcmp()不正确,因为它可能会超出其最后一个元素访问s。您应该使用strncmp()代替或添加长度测试。

  • 发布的代码找不到空子字符串的最后一次出现并返回NULL,它应返回指向尾随空字节的指针。

  • 为了保持一致性,您应该将其称为strrstr()my_strrstr()

这是一个更快更安全的版本:

char *my_strrstr(const char *s, const char *m) {
    char *last = NULL;
    size_t n = strlen(m);

    while ((s = strchr(s, *m)) != NULL) {
        if (!strncmp(s, m, n))
            last = (char *)s;
        if (*s++ == '\0')
            break;
    }
    return last;
}
相关问题