简体   繁体   中英

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?

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.

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, eg 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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM