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

后端 未结 8 1516
自闭症患者
自闭症患者 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 06:03

    Optimized (v.2. - corrected):

    uint32 startsWith( const void* prefix_, const void* str_ ) {
        uint8 _cp, _cs;
        const uint8* _pr = (uint8*) prefix_;
        const uint8* _str = (uint8*) str_;
        while ( ( _cs = *_str++ ) & ( _cp = *_pr++ ) ) {
            if ( _cp != _cs ) return 0;
        }
        return !_cp;
    }
    
    0 讨论(0)
  • 2020-11-30 06:04

    I'm no expert at writing elegant code, but...

    int prefix(const char *pre, const char *str)
    {
        char cp;
        char cs;
    
        if (!*pre)
            return 1;
    
        while ((cp = *pre++) && (cs = *str++))
        {
            if (cp != cs)
                return 0;
        }
    
        if (!cs)
            return 0;
    
        return 1;
    }
    
    0 讨论(0)
提交回复
热议问题