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


当前回答

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

其他回答

使用Boost。Text,它将适用于Unicode文本

boost::text::text t = "Hello World";
boost::text::text uppered;
boost::text::to_title(t, std::inserter(uppered, uppered.end()));
std::string newstr = uppered.extract();

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

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

如果你只使用ASCII字符,速度会更快:

for(i=0;str[i]!=0;i++)
  if(str[i]<='z' && str[i]>='a')
    str[i]+='A'-'a';

请注意,这段代码运行得更快,但只适用于ASCII,不是一个“抽象”的解决方案。

其他UTF8字母的扩展版本:

...
if(str[i]<='z' && str[i]>='a') //is latin
    str[i]+='A'-'a';
else if(str[i]<='я' && str[i]>='а') //cyrillic
    str[i]+='Я'-'я'
else if(str[i]<='ω' && str[i]>='α') //greek
    str[i]+='Ω'-'ω'
//etc...

如果您需要完整的UNICODE解决方案或更传统和抽象的解决方案,请寻找其他答案并使用c++字符串的方法。