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


当前回答

Boost字符串算法:

#include <boost/algorithm/string.hpp>
#include <string>

std::string str = "Hello World";

boost::to_upper(str);

std::string newstr = boost::to_upper_copy<std::string>("Hello World");

其他回答

尝试toupper()函数(#include <ctype.h>)。它接受字符作为参数,字符串是由字符组成的,所以你必须遍历每个单独的字符,当它们放在一起组成字符串时

#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());

使用c++ 11和toupper()的简单解决方案。

for (auto & c: str) c = toupper(c);
//works for ASCII -- no clear advantage over what is already posted...

std::string toupper(const std::string & s)
{
    std::string ret(s.size(), char());
    for(unsigned int i = 0; i < s.size(); ++i)
        ret[i] = (s[i] <= 'z' && s[i] >= 'a') ? s[i]-('a'-'A') : s[i];
    return ret;
}
#include <algorithm>
#include <string>

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