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


当前回答

#include <algorithm>
#include <string>

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

其他回答

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

#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循环

@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!

字符串中有ASCII或国际字符吗?

如果是后一种情况,“大写字母”就没那么简单了,这取决于使用的字母。有两院制和一院制的字母。只有两院制的字母有不同的大小写字符。此外,还有复合字符,如拉丁大写字母'DZ' (\u01F1 'DZ'),它们使用所谓的标题大小写。这意味着只有第一个字符(D)被改变。

我建议你看看ICU,以及简单病例映射和全病例映射之间的区别。这可能会有帮助:

http://userguide.icu-project.org/transforms/casemappings

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

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

这是c++ 11的最新代码

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