I'm doing a search for a substring in a string and I don't want it to be case sensitive. Is there either a case insensitive search (im using the string class) or a way to convert a string to lowercase?
I'm doing a search for a substring in a string and I don't want it to be case sensitive. Is there either a case insensitive search (im using the string class) or a way to convert a string to lowercase?
Some compilers have a non standard function called strlower() that takes in a string and converts it to lowercase. If your compiler doesn't have it you can make your own:
I don't know of any case insenstive sub string search but you could define your own:Code:char* strlower(char *s) { char *p = s; for(; *p; p++) *p = tolower( (unsigned char) *p ); return s; }
Code:char* stristr(const char *haystack, const char *needle) { /* Make a deep copy of haystack */ /* Convert the copy to lowercase */ /* use strstr() and capture the return value */ /* use the return value to find the offset on the orginal string */ /* free the copy */ /* return the result */ }
here's a standard way using namespace std:
string str22 = "AbcdEFG hIJKlmnOPQRSTUVwxyZ";
transform (str22.begin(),str22.end(), str22.begin(), tolower);
>transform (str22.begin(),str22.end(), str22.begin(), tolower);
Technically that's broken depending on the headers you include. Both iostream and cctype declare tolower, but with different arguments. So if you include iostream and cctype (not exactly an unlikely occurance) and try to use this function call, the compiler would be well within its rights to refuse to compile it due to ambiguous declarations of tolower. Your compiler might accept it, but that just means your code is non-portable. And before you consider it, a typecast would be equally broken. You can fix the problem by explicitly telling the compiler which version of tolower you want:
Code:#include <algorithm> #include <cctype> #include <iostream> #include <string> struct lower_case { int operator() ( int c ) { return std::tolower ( c ); } }; int main() { std::string s = "THIS IS A TEST"; std::transform ( s.begin(), s.end(), s.begin(), lower_case() ); std::cout<< s <<'\n'; }
My best code is written with the delete key.