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


当前回答

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)

其他回答

只要你能接受ascii,并且你可以提供一个指向RW内存的有效指针,在C语言中有一个简单而有效的一行代码:

void strtoupper(char* str)
{ 
    while (*str) *(str++) = toupper((unsigned char)*str);
}

这对于像ASCII标识符这样的简单字符串特别有用,您希望将其规范化为相同的字符大小写。然后你可以使用缓冲区来构造一个std:string实例。

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

包括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;
}
//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;

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