Search code examples
c++c-stringsstrchr

Are there any modern alternatives of std::strchr() for C++?


I am extensively using std::strchr() in my code, but recently i started thinking about making my code more readable and modern. I wish there was function similar to std::any_of/std::string::find_first_of which is taking single character instead of containers. So i am questioning myself how to "update" my code to C++17.

while (std::strchr("abcd", input) == nullptr) { //how to get rid of this C function?
        //do smth
}

Any ideas?

Thanks, have a nice day!


Solution

  • There is no sense to update your code because the string literal has a type of a character array.

    It would be a bad idea to create an intermediate object of for example std::string to perform such a simple task.

    With c-strings declared like arrays use C string functions. C string functions are optimized and sometimes are performed by using just a pair of machine instructions.

    With other containers use their member functions or standard algorithms.

    Compare for example two approaches

    const char *s = "abcd";
    
    const char *p = strchr( s, c );
    
    if ( p )
    {
        //...
    }
    

    Or even like

    const char *s = "abcd";
    
    if ( const char *p = strchr( s, c ) )
    {
        //...
    }
    

    and

    const char *s = "abcd";
    size_t n = std::strlen( s );
    
    auto it = std::find( s, s + n, c );
    
    if ( it != s + n )
    {
        //...
    }
    

    Or less readable in C++ 17

    const char *s = "abcd";
    size_t n = std::strlen( s );
    
    if ( auto it = std::find( s, s + n, c ); it != s + n )
    {
        //...
    }
    

    It is evident that the first approach is more efficient.

    On the other hand, if you have a general function that should accept c-strings and/or objects of the type std::string then if the function does not change them then use std::string_view as a function parameter.