Is there exist a case-insensitive find()
method for std::string
?
Yes. C++ is case sensitive. Because the code are then compiled and each character has a different code.
The find() method performs case-sensitive search. It returns -1 if a substring is not found.
The strcasecmp() function performs a byte-by-byte comparison of the strings s1 and s2, ignoring the case of the characters. It returns an integer less than, equal to, or greater than zero if s1 is found, respectively, to be less than, to match, or be greater than s2.
You could upper-case both strings and use the regular find. (Note: this approach may not be correct if you have Unicode string.)
In Boost there's also ifind_first
for case-insensitive search. (note that it returns a range instead of a size_t
).
#include <string>
#include <boost/algorithm/string/find.hpp>
#include <cstdio>
#include <cctype>
std::string upperCase(std::string input) {
for (std::string::iterator it = input.begin(); it != input.end(); ++ it)
*it = toupper(*it);
return input;
}
int main () {
std::string foo = "1 FoO 2 foo";
std::string target = "foo";
printf("string.find: %zu\n", foo.find(target));
printf("string.find w/ upperCase: %zu\n", upperCase(foo).find(upperCase(target)));
printf("ifind_first: %zu\n", boost::algorithm::ifind_first(foo, target).begin() - foo.begin());
return 0;
}
this is what I would have suggested, (the same as @programmersbook)
#include <iostream>
#include <algorithm>
#include <string>
bool lower_test (char l, char r) {
return (std::tolower(l) == std::tolower(r));
}
int main()
{
std::string text("foo BaR");
std::string search("bar");
std::string::iterator fpos = std::search(text.begin(), text.end(), search.begin(), search.end(), lower_test);
if (fpos != text.end())
std::cout << "found at: " << std::distance(text.begin(), fpos) << std::endl;
return 0;
}
Before doing anything fancy, have a look at
http://www.gotw.ca/gotw/029.htm
and see if using a custom character traits class is not what you want.
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