Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which is better to check if a character exists in a std::string? find or find_first_of?

std::string has two different member functions that do the same thing:

size_type find( CharT ch, size_type pos = 0 ) const noexcept;
size_type find_first_of( CharT ch, size_type pos = 0 ) const noexcept;

If I want to check if a character exists in a std::string, which one is preferred in terms of performance?

like image 984
xmllmx Avatar asked Feb 01 '26 23:02

xmllmx


2 Answers

It doesn't matter. They do the same thing.

Like, literally. libstdc++ just delegates find_first_of(char, size_t) to find(char, size_t), as does libc++, and MSVS 2015 too (thanks roalz). There's no reason for any implementation to do otherwise.

I'm not really clear on why that overload of find_first_of even exists; it could just be for symmetry with find (which does something different when you use the other overloads) but to be honest that just seems confusing to me.

like image 75
Lightness Races in Orbit Avatar answered Feb 03 '26 13:02

Lightness Races in Orbit


They are pretty much identical. But not doing the exact same thing in some specific case and that is depends what std library you are using.

I am using a thing called EWL, (highly likely no 1 is using this anymore) in that library string::find() and string::find_first_of are the same.

But different libraries have different stories. In some library, e.g Gnu, C++2a, if you searching an empty string from an empty string, std::find() returns position 0. However std::find_first_of() returns std::string::npos. They are right or wrong depends on the different views you have.

The issue is discussed here.

like image 44
r0n9 Avatar answered Feb 03 '26 11:02

r0n9



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!