faster strlen?

后端 未结 8 2324
小鲜肉
小鲜肉 2021-02-20 15:49

Typical strlen() traverse from first character till it finds \\0. This requires you to traverse each and every character. In algorithm sense, its O(N).

8条回答
  •  我在风中等你
    2021-02-20 16:03

    Jack,

    strlen works by looking for the ending '\0', here's an implementation taken from OpenBSD:

    size_t
    strlen(const char *str)
    {
            const char *s;
    
            for (s = str; *s; ++s)
                    ;
            return (s - str);
    }
    

    Now, consider that you know the length is about 200 characters, as you said. Say you start at 200 and loop up and down for a '\0'. You've found one at 204, what does it mean? That the string is 204 chars long? NO! It could end before that with another '\0' and all you did was look out of bounds.

提交回复
热议问题