Find Functions

Hey guys,

int pos = name.find('t');
int pos2 = name.find('T');
if (pos == string::npos && pos2 == string::npos) {
cout << "There is no t in your name" << endl;
}
else if (pos > 0) {
cout << "t is in position " << pos << endl;
}

else {
cout << "T is in position " << pos2 << endl;
}

Is there a easier way, or more efficient way to find both a lowercase and upper case t? I'm new to programming, any help would be appreciated.

Thanks
You could convert the string to lowercase first and then just search for lowercase letters. If you need to know the case of the original letter, just look at it in the same index in the original string.

As for converting a string to lowercase in C++, a quick Google search should give you the info you need - just be aware that it's a lot harder if you want to support other languages with UTF-8. In some languages, a letter in one case corresponds to two letters in the opposite case.

EDIT: JLBorges gives a better solution below.
Last edited on
Using stl transform:

1
2
3
std:string s = "This HAS Mixed Up CAse";

std::transform( s.begin(), s.end(), s.begin, ::tolower );


Which, frequently, is done on a copy of s instead of s itself.

> Is there a easier way, or more efficient way to find both a lower case and upper case t?

1
2
// http://www.cplusplus.com/reference/string/string/find_first_of/
if( name.find_first_of( "tT" ) != std::string::npos ) { /* ... */ }
look at the ascii table : upper case letter start from 41 to 90 , then lower case letter start at 97 to 122 . So simply do something like :

1
2
3
4
5
6
7
const char letterToFind = 'T';
for(size_t i=0;i<name.size();++i)
{
   const char letter = name[i];
    if(letter == letterToFind || letter == letterToFind + 32)
        return true;
}
@Ericool: don't rely on the numeric values of characters, as they are not the same on all systems and environments.
@LB I agree on that ;)
Topic archived. No new replies allowed.