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


当前回答

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

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

其他回答

template<size_t size>
char* toupper(char (&dst)[size], const char* src) {
    // generate mapping table once
    static char maptable[256];
    static bool mapped;
    if (!mapped) {
        for (char c = 0; c < 256; c++) {
            if (c >= 'a' && c <= 'z')
                maptable[c] = c & 0xdf;
            else
                maptable[c] = c;
        }
        mapped = true;
    }

    // use mapping table to quickly transform text
    for (int i = 0; *src && i < size; i++) {
        dst[i] = maptable[*(src++)];
    }
    return dst;
}
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。)

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

只要你能接受ascii,并且你可以提供一个指向RW内存的有效指针,在C语言中有一个简单而有效的一行代码:

void strtoupper(char* str)
{ 
    while (*str) *(str++) = toupper((unsigned char)*str);
}

这对于像ASCII标识符这样的简单字符串特别有用,您希望将其规范化为相同的字符大小写。然后你可以使用缓冲区来构造一个std:string实例。

这个c++函数总是返回大写字符串…

#include <locale> 
#include <string>
using namespace std; 
string toUpper (string str){
    locale loc; 
    string n; 
    for (string::size_type i=0; i<str.length(); ++i)
        n += toupper(str[i], loc);
    return n;
}