如何将字符串转换为大写。我从谷歌上找到的例子只涉及字符。


当前回答

#include <string>
#include <locale>

std::string str = "Hello World!";
auto & f = std::use_facet<std::ctype<char>>(std::locale());
f.toupper(str.data(), str.data() + str.size());

这将比使用全局toupper函数的所有答案执行得更好,并且可能是boost::to_upper在下面所做的事情。

这是因为::toupper必须为每次调用查找区域设置——因为它可能已经被不同的线程更改了——而这里只有对locale()的调用有这个惩罚。查找区域通常需要锁。

这也适用于c++ 98,在你替换auto后,使用新的非const str.data(),并添加一个空格来打破模板结束符(“>>”到“>>”),如下所示:

std::use_facet<std::ctype<char> > & f = 
    std::use_facet<std::ctype<char> >(std::locale());
f.toupper(const_cast<char *>(str.data()), str.data() + str.size());

其他回答

@dirkgently的回答非常鼓舞人心,但我想强调的是,出于如下所示的担忧,

与from的所有其他函数一样,如果实参的值既不能表示为unsigned char也不等于EOF,则std::toupper的行为是未定义的。为了安全地将这些函数与普通字符(或有符号字符)一起使用,参数首先应该转换为无符号字符 参考:std:: toupper

由于标准没有指定plain char是带符号的还是无符号的[1], std::toupper的正确用法应该是:

#include <algorithm>
#include <cctype>
#include <iostream>
#include <iterator>
#include <string>

void ToUpper(std::string& input)
{
    std::for_each(std::begin(input), std::end(input), [](char& c) {
        c = static_cast<char>(std::toupper(static_cast<unsigned char>(c)));
    });
}

int main()
{
    std::string s{ "Hello world!" };
    std::cout << s << std::endl;
    ::ToUpper(s);
    std::cout << s << std::endl;

    return 0;
}

输出:

Hello world!
HELLO WORLD!
typedef std::string::value_type char_t;

char_t up_char( char_t ch )
{
    return std::use_facet< std::ctype< char_t > >( std::locale() ).toupper( ch );
}

std::string toupper( const std::string &src )
{
    std::string result;
    std::transform( src.begin(), src.end(), std::back_inserter( result ), up_char );
    return result;
}

const std::string src  = "test test TEST";

std::cout << toupper( src );

这是c++ 11的最新代码

std::string cmd = "Hello World";
for_each(cmd.begin(), cmd.end(), [](char& in){ in = ::toupper(in); });
#include <algorithm>
#include <string>

std::string str = "Hello World";
std::transform(str.begin(), str.end(),str.begin(), ::toupper);

不使用任何库:

std::string YourClass::Uppercase(const std::string & Text)
{
    std::string UppperCaseString;
    UppperCaseString.reserve(Text.size());
    for (std::string::const_iterator it=Text.begin(); it<Text.end(); ++it)
    {
        UppperCaseString.push_back(((0x60 < *it) && (*it < 0x7B)) ? (*it - static_cast<char>(0x20)) : *it);
    }
    return UppperCaseString;
}