I would like to implement a string comparison in C++ comparing strings up to a "%" sign.
I could do it like this:
std::equal(str1.begin(),
std::find(str1.begin(), str1.end(), L'%'),
str2.begin());
Since I'm doing this in a loop over many strings, I wonder if there is a method without two distinct string traversals for find
and equal
(maybe with a predicate that can abort the comparison at any point). Boost is ok.
String comparison by Using String Library Functionstrcmp() function is used to compare two strings. The strcmp() function takes two strings as input and returns an integer result that can be zero, positive, or negative. The strcmp() function compares both strings characters.
You can't compare strings in C with ==, because the C compiler does not really have a clue about strings beyond a string-literal.
You should not use == (equality operator) to compare these strings because they compare the reference of the string, i.e. whether they are the same object or not. On the other hand, equals() method compares whether the value of the strings is equal, and not the object itself.
The comparison operators also work on strings. To see if two strings are equal you simply write a boolean expression using the equality operator.
You can try std::mismatch
.
The following code will run with C++14 (it requires the template overload with two iterator pairs), but it works quite similar in C++11 (or 03, without lambdas though):
auto iters = std::mismatch( str1.begin(), str1.end(), str2.begin(), str2.end(),
[] (char lhs, char rhs) {return lhs != '%' && lhs == rhs;});
if (iters.first == str1.end()
|| iters.second == str2.end()
|| *iters.first == '%')
// Success […]
Demo.
Here's a hackish way of doing it:
auto it = std::find_if(
str1.begin(), str1.end(),
[&str2](const char &c) {
return c == '%' || str2[&c - &str1[0]] != c
}
);
bool equal = (it == str1.end() || *it == '%');
The idea is to create a predicate "character is the same as in the other string and not a '%'
."
It relies on str2
being long enough, but so does the code in the question.
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