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


当前回答

如果你只想大写,试试这个函数。

#include <iostream>


using namespace std;

string upper(string text){
    string upperCase;
    for(int it : text){
        if(it>96&&it<123){
            upperCase += char(it-32);
        }else{
            upperCase += char(it);
        }
    }
    return upperCase;
}

int main() {
    string text = "^_abcdfghopqrvmwxyz{|}";
    cout<<text<<"/";
    text = upper(text);
    cout<<text;
    return 0;
}

错误:在c++ 98模式中不允许基于范围的for循环

其他回答

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

本页上的所有这些解决方案都比它们需要的要难。

这样做

RegName = "SomE StRing That you wAnt ConvErTed";
NameLength = RegName.Size();
for (int forLoop = 0; forLoop < NameLength; ++forLoop)
{
     RegName[forLoop] = tolower(RegName[forLoop]);
}

RegName是你的字符串。 获取字符串大小不要使用string.size()作为实际的测试器,非常混乱 可能会引起问题。 然后。最基本的for循环。

记住,字符串大小也返回分隔符,所以在循环测试中使用<而不是<=。

输出将是: 你想转换的字符串

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

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

不使用任何库:

std::string YourClass::Uppercase(const std::string & Text)
{
    std::string UppperCaseString;
    UppperCaseString.reserve(Text.size());
    for (std::string::const_iterator it=Text.begin(); it<Text.end(); ++it)
    {
        UppperCaseString.push_back(((0x60 < *it) && (*it < 0x7B)) ? (*it - static_cast<char>(0x20)) : *it);
    }
    return UppperCaseString;
}

这是c++ 11的最新代码

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