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


当前回答

下面的方法对我有用。

#include <algorithm>
void  toUpperCase(std::string& str)
{
    std::transform(str.begin(), str.end(), str.begin(), ::toupper);
}

int main()
{
   std::string str = "hello";
   toUpperCase(&str);
}

其他回答

如果你只使用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++字符串的方法。

不确定是否有内置功能。试试这个:

包括ctype.h或cctype库,以及stdlib.h作为预处理器指令的一部分。

string StringToUpper(string strToConvert)
{//change each element of the string to upper case
   for(unsigned int i=0;i<strToConvert.length();i++)
   {
      strToConvert[i] = toupper(strToConvert[i]);
   }
   return strToConvert;//return the converted string
}

string StringToLower(string strToConvert)
{//change each element of the string to lower case
   for(unsigned int i=0;i<strToConvert.length();i++)
   {
      strToConvert[i] = tolower(strToConvert[i]);
   }
   return strToConvert;//return the converted string
}
template<size_t size>
char* toupper(char (&dst)[size], const char* src) {
    // generate mapping table once
    static char maptable[256];
    static bool mapped;
    if (!mapped) {
        for (char c = 0; c < 256; c++) {
            if (c >= 'a' && c <= 'z')
                maptable[c] = c & 0xdf;
            else
                maptable[c] = c;
        }
        mapped = true;
    }

    // use mapping table to quickly transform text
    for (int i = 0; *src && i < size; i++) {
        dst[i] = maptable[*(src++)];
    }
    return dst;
}

这是c++ 11的最新代码

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

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