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


当前回答

这是c++ 11的最新代码

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

其他回答

我用这个解。我知道你不应该修改数据区域....但我认为这主要是缓冲区溢出错误和空字符....大写字母就不一样了。

void to_upper(const std::string str) {
    std::string::iterator it;
    int i;
    for ( i=0;i<str.size();++i ) {
        ((char *)(void *)str.data())[i]=toupper(((char *)str.data())[i]);
    }
}
struct convert {
   void operator()(char& c) { c = toupper((unsigned char)c); }
};

// ... 
string uc_str;
for_each(uc_str.begin(), uc_str.end(), convert());

注意:顶部解决方案的几个问题:

21.5以空结束的序列实用程序 这些头文件的内容应该与标准C库头文件相同<ctype.h>, <wctype.h>, <string.h>, <wchar.h>,和<stdlib.h>[…]

这意味着cctype成员很可能是不适合在标准算法中直接使用的宏。 同一个例子的另一个问题是,它没有强制转换实参,也没有验证它是非负的;这对于使用纯char符号的系统尤其危险。(原因是:如果这是作为一个宏实现的,它可能会使用一个查找表和你的参数索引到那个表。负指数会给你UB。)

std::string value;
for (std::string::iterator p = value.begin(); value.end() != p; ++p)
    *p = toupper(*p);

不使用任何库:

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;
}

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");