Suppose I have a string and I want to find whether a specific character (like '|') is present or not, what is the best and fastest technique to do so? I know string find implementation.I am asking for even faster implementation than this one.
Use the String. includes() method to check if a string contains a character, e.g. if (str. includes(char)) {} . The include() method will return true if the string contains the provided character, otherwise false is returned.
The strchr() function finds the first occurrence of a character in a string. The character c can be the null character (\0); the ending null character of string is included in the search. The strchr() function operates on null-ended strings.
Check if a string contains a sub-string in C++ This find() method returns the first location where the string is found. Here we are using this find() function multiple times to get all of the matches. If the item is found, this function returns the position. But if it is not found, it will return string::npos.
The includes() method returns true if a string contains a specified string. Otherwise it returns false .
Use std::string::find
if (str.find('|') != std::string::npos)
{
// ...
}
There's unlikely to be anything more efficient. O(n) is the best you can do. The standard library implementation should be pretty much optimal.
From this source empirical test done with Visual Studio 2013 Compiler shows that strchr routine is about 2x faster than std::string::find implementation.
Adding on the answer of Tom Tanner. If you don't want to do any a priori calculations you will be stuck at O(n), ie there is a linear correlation between the length of the string you are searching in and the time consumption. Tom suggested to set up an array (or vector) of booleans that indicate whether a certain character occurred. It would need O(n) once to index the string, but then you can check for any number of characters in O(1) (constant time) if it is included. The downside with this approach is that you will need a lot of memory (once you decide you need to support unicode).
As a compromise you could use a std::set or similar, storing only the characters that actually exist in your input string. Memory consumption would then be around linear with regard to the number of different characters in the string but lookup would be O(log n), ie logarithmic in time.
Of course you should measure/profile and then explain here what use case you are actually optimizing for. Until you have done so, stick with what is easiest to understand and read.
Another way is to use the strchr function on the corresponding c_str string:
if(strchr(str.c_str(), '|'))
{
\\found
}
Not sure how it compares to std find in terms of speed though...
The position of the found character is
size_t pos = strchr(str.c_str(),'|') - str.c_str();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With