How to check if a string starts with another string in C?

后端 未结 8 1542
自闭症患者
自闭症患者 2020-11-30 05:09

Is there something like startsWith(str_a, str_b) in the standard C library?

It should take pointers to two strings that end with nullbytes, and tell me

8条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-30 05:48

    Because I ran the accepted version and had a problem with a very long str, I had to add in the following logic:

    bool longEnough(const char *str, int min_length) {
        int length = 0;
        while (str[length] && length < min_length)
            length++;
        if (length == min_length)
            return true;
        return false;
    }
    
    bool startsWith(const char *pre, const char *str) {
        size_t lenpre = strlen(pre);
        return longEnough(str, lenpre) ? strncmp(str, pre, lenpre) == 0 : false;
    }
    

提交回复
热议问题