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


当前回答

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

for (auto & c: str) c = toupper(c);

其他回答

如果你只想大写,试试这个函数。

#include <iostream>


using namespace std;

string upper(string text){
    string upperCase;
    for(int it : text){
        if(it>96&&it<123){
            upperCase += char(it-32);
        }else{
            upperCase += char(it);
        }
    }
    return upperCase;
}

int main() {
    string text = "^_abcdfghopqrvmwxyz{|}";
    cout<<text<<"/";
    text = upper(text);
    cout<<text;
    return 0;
}

错误:在c++ 98模式中不允许基于范围的for循环

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

for (auto & c: str) c = toupper(c);
#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;
}

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

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

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