且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何比较字符串的两端用C?

更新时间:2023-11-10 10:42:34

不要调用strlen不止一次每串。

  INT的endsWith(为const char * str中,为const char *后缀)
{
    如果(!STR ||!后缀)
        返回0;
    为size_t len​​str = strlen的(STR);
    为size_t len​​suffix = strlen的(后缀);
    如果(lensuffix> lenstr)
        返回0;
    返回STRNCMP(STR + lenstr - lensuffix,后缀,lensuffix)== 0;
}INT EndsWithFoo(为const char * STR){返回的endsWith(STR,包含.foo); }

编辑:为迂腐添加NULL检查。对于超迂腐,讨论是否应该返回非零值,如果这两个海峡和后缀都是NULL。

I want to make sure my string ends with ".foo". I am using C, a language I am not totally familiar with. The best way I have found to do it is below. Any C gurus want to make sure I'm doing this elegantly and wisely?

int EndsWithFoo(char *str)
{
    if(strlen(str) >= strlen(".foo"))
    {
        if(!strcmp(str + strlen(str) - strlen(".foo"), ".foo"))
        {
            return 1;
        }
    }
    return 0;
}

Don't call strlen more than once per string.

int EndsWith(const char *str, const char *suffix)
{
    if (!str || !suffix)
        return 0;
    size_t lenstr = strlen(str);
    size_t lensuffix = strlen(suffix);
    if (lensuffix >  lenstr)
        return 0;
    return strncmp(str + lenstr - lensuffix, suffix, lensuffix) == 0;
}

int EndsWithFoo(const char *str) { return EndsWith(str, ".foo"); }

EDIT: added NULL check for the pedantic. For the ultra pedantic, debate whether it should return non-zero if both str and suffix are both NULL.