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


当前回答

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。)

其他回答

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

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

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

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

使用lambda。

std::string s("change my case");

std::locale locale;
auto to_upper = [&locale] (char ch) { return std::use_facet<std::ctype<char>>(locale).toupper(ch); };

std::transform(s.begin(), s.end(), s.begin(), to_upper);

使用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();
std::string str = "STriNg oF mIxID CasE lETteRS"

C + 11 +

使用for_each std:: for_each (str.begin (), str.end (), [] (char & c) {c =: toupper (c);}); 使用转换 std::变换(str.begin (), str.end (), str.begin ():: toupper);

c++(仅限windows)

_strupr_s(str, str.length());

c++(使用Boost库)

boost::to_upper_copy(str)
#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());