Convert a String In C++ To Upper Case

后端 未结 30 1508
一个人的身影
一个人的身影 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:04
    #include <algorithm>
    #include <string>
    
    std::string str = "Hello World";
    std::transform(str.begin(), str.end(),str.begin(), ::toupper);
    
    0 讨论(0)
  • 2020-11-22 06:04

    Short solution using C++11 and toupper().

    for (auto & c: str) c = toupper(c);
    
    0 讨论(0)
  • 2020-11-22 06:04
    //works for ASCII -- no clear advantage over what is already posted...
    
    std::string toupper(const std::string & s)
    {
        std::string ret(s.size(), char());
        for(unsigned int i = 0; i < s.size(); ++i)
            ret[i] = (s[i] <= 'z' && s[i] >= 'a') ? s[i]-('a'-'A') : s[i];
        return ret;
    }
    
    0 讨论(0)
  • 2020-11-22 06:07
    typedef std::string::value_type char_t;
    
    char_t up_char( char_t ch )
    {
        return std::use_facet< std::ctype< char_t > >( std::locale() ).toupper( ch );
    }
    
    std::string toupper( const std::string &src )
    {
        std::string result;
        std::transform( src.begin(), src.end(), std::back_inserter( result ), up_char );
        return result;
    }
    
    const std::string src  = "test test TEST";
    
    std::cout << toupper( src );
    
    0 讨论(0)
  • 2020-11-22 06:07

    This c++ function always returns the upper case string...

    #include <locale> 
    #include <string>
    using namespace std; 
    string toUpper (string str){
        locale loc; 
        string n; 
        for (string::size_type i=0; i<str.length(); ++i)
            n += toupper(str[i], loc);
        return n;
    }
    
    0 讨论(0)
  • 2020-11-22 06:09

    As long as you are fine with ASCII-only and you can provide a valid pointer to RW memory, there is a simple and very effective one-liner in C:

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

    This is especially good for simple strings like ASCII identifiers which you want to normalize into the same character-case. You can then use the buffer to construct a std:string instance.

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