Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 258
JoJo Avatar asked Oct 16 '25 14:10

JoJo


2 Answers

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.

like image 90
Vlad from Moscow Avatar answered Oct 19 '25 13:10

Vlad from Moscow


You can use std::find with a string, or std::strings very own std::string::find.

like image 45
SergeyA Avatar answered Oct 19 '25 13:10

SergeyA



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!