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

后端 未结 8 1562
自闭症患者
自闭症患者 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:57

    Or a combination of the two approaches:

    _Bool starts_with(const char *restrict string, const char *restrict prefix)
    {
        char * const restrict prefix_end = prefix + 13;
        while (1)
        {
            if ( 0 == *prefix  )
                return 1;   
            if ( *prefix++ != *string++)
                return 0;
            if ( prefix_end <= prefix  )
                return 0 == strncmp(prefix, string, strlen(prefix));
        }  
    }
    

    EDIT: The code below does NOT work because if strncmp returns 0 it is not known if a terminating 0 or the length (block_size) was reached.

    An additional idea is to compare block-wise. If the block is not equal compare that block with the original function:

    _Bool starts_with_big(const char *restrict string, const char *restrict prefix)
    {
        size_t block_size = 64;
        while (1)
        {
            if ( 0 != strncmp( string, prefix, block_size ) )
              return starts_with( string, prefix);
            string += block_size;
            prefix += block_size;
            if ( block_size < 4096 )
              block_size *= 2;
        }
    }
    

    The constants 13, 64, 4096, as well as the exponentiation of the block_size are just guesses. It would have to be selected for the used input data and hardware.

提交回复
热议问题