Hm, three answers here managed to use tolower
incorrectly.
Its argument must be non-negative or the special EOF
value, otherwise Undefined Behavior. If all you have are ASCII characters then the codes will all be non-negative, so in that special case, it can be used directly. But if there's any non-ASCII character, like in Norwegian "blåbærsyltetøy" (blueberry jam), then those codes are most likely negative, so casting the argument to unsigned char
type is necessary.
Also, for this case, the C locale should be set to the relevant locale.
E.g., you can set it to the user's default locale, which is denoted by an empty string as argument to setlocale
.
Example:
#include <iostream>
#include <string> // std::string
#include <ctype.h> // ::tolower
#include <locale.h> // ::setlocale
#include <stddef.h> // ::ptrdiff_t
typedef unsigned char UChar;
typedef ptrdiff_t Size;
typedef Size Index;
char toLowerCase( char c )
{
return char( ::tolower( UChar( c ) ) ); // Cast to unsigned important.
}
std::string toLowerCase( std::string const& s )
{
using namespace std;
Size const n = s.length();
std::string result( n, '\0' );
for( Index i = 0; i < n; ++i )
{
result[i] = toLowerCase( s[i] );
}
return result;
}
int main()
{
using namespace std;
setlocale( LC_ALL, "" ); // Setting locale important.
cout << toLowerCase( "SARAH CONNER LIKES BLÅBÆRSYLTETØY" ) << endl;
}
Example of instead doing this using std::transform
:
#include <iostream>
#include <algorithm> // std::transform
#include <functional> // std::ptr_fun
#include <string> // std::string
#include <ctype.h> // ::tolower
#include <locale.h> // ::setlocale
#include <stddef.h> // ::ptrdiff_t
typedef unsigned char UChar;
char toLowerCase( char c )
{
return char( ::tolower( UChar( c ) ) ); // Cast to unsigned important.
}
std::string toLowerCase( std::string const& s )
{
using namespace std;
string result( s.length(), '\0' );
transform( s.begin(), s.end(), result.begin(), ptr_fun<char>( toLowerCase ) );
return result;
}
int main()
{
using namespace std;
setlocale( LC_ALL, "" ); // Setting locale important.
cout << toLowerCase( "SARAH CONNER LIKES BLÅBÆRSYLTETØY" ) << endl;
}
For an example of using the C++ level locale stuff instead of C locale, see Johannes' answer.
Cheers & hth.,