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


当前回答

使用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。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();

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

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

//Since I work on a MAC, and Windows methods mentioned do not work for me, I //just built this quick method.


string str; 
    str = "This String Will Print Out in all CAPS";
    int len = str.size(); 
    char b;

for (int i = 0; i < len; i++){
    b = str[i]; 
    b = toupper(b); 
   // b = to lower(b); //alternately 
     str[i] = b;    
}
    

cout<<str;

使用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);