Convert a String In C++ To Upper Case

后端 未结 30 1510
一个人的身影
一个人的身影 2020-11-22 05:25

How could one convert a string to upper case. The examples I have found from googling only have to deal with chars.

相关标签:
30条回答
  • 2020-11-22 06:09
    std::string value;
    for (std::string::iterator p = value.begin(); value.end() != p; ++p)
        *p = toupper(*p);
    
    0 讨论(0)
  • 2020-11-22 06:11
    string StringToUpper(string strToConvert)
    {
       for (std::string::iterator p = strToConvert.begin(); strToConvert.end() != p; ++p)
           *p = toupper(*p);
    
       return p;
    }
    

    Or,

    string StringToUpper(string strToConvert)
    {
        std::transform(strToConvert.begin(), strToConvert.end(), strToConvert.begin(), ::toupper);
    
        return strToConvert;
    }
    
    0 讨论(0)
  • 2020-11-22 06:11

    Here is the latest code with C++11

    std::string cmd = "Hello World";
    for_each(cmd.begin(), cmd.end(), [](char& in){ in = ::toupper(in); });
    
    0 讨论(0)
  • 2020-11-22 06:12

    Boost string algorithms:

    #include <boost/algorithm/string.hpp>
    #include <string>
    
    std::string str = "Hello World";
    
    boost::to_upper(str);
    
    std::string newstr = boost::to_upper_copy<std::string>("Hello World");
    
    0 讨论(0)
  • 2020-11-22 06:12

    The following works for me.

    #include <algorithm>
    void  toUpperCase(std::string& str)
    {
        std::transform(str.begin(), str.end(), str.begin(), ::toupper);
    }
    
    int main()
    {
       std::string str = "hello";
       toUpperCase(&str);
    }
    
    0 讨论(0)
  • 2020-11-22 06:12

    ALL of these solutions on this page are harder than they need to be.

    Do this

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

    RegName is your string. Get your string size don't use string.size() as your actual tester, very messy and can cause issues. then. the most basic for loop.

    remember string size returns the delimiter too so use < and not <= in your loop test.

    output will be: some string that you want converted

    0 讨论(0)
提交回复
热议问题