嗯,这里的三个答案都用tolower
错了。
其参数必须为非负数或特殊EOF
值,否则为未定义行为。如果你只有 ASCII 字符,那么代码都是非负的,所以在这种特殊情况下,它可以直接使用。但是,如果有任何非 ASCII 字符,例如挪威语“blåbærsyltetøy”(蓝莓果酱),那么这些代码很可能是负数,因此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.,