うーん、ここでの3つの答えはtolower
間違って使用することができました。
その引数は、非負または特別なEOF
値である必要があります。そうでない場合、未定義動作です。持っているのがASCII文字だけの場合、コードはすべて負ではないため、その特殊なケースでは、直接使用できます。ただし、ノルウェー語の「blåbærsyltetøy」(ブルーベリージャム)のようにASCII以外の文字がある場合、それらのコードはおそらく負であるため、引数をunsignedtypeにキャストするchar
必要があります。
また、この場合、Cロケールを関連するロケールに設定する必要があります。
たとえば、ユーザーのデフォルトロケールに設定できます。これは、の引数として空の文字列で示されますsetlocale
。
例:
#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;
}
代わりに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;
}
Cロケールの代わりにC++レベルのロケールのものを使用する例については、Johannesの回答を参照してください。
乾杯&hth。、