Convert a String In C++ To Upper Case

后端 未结 30 1871
一个人的身影
一个人的身影 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:01

    #include 
    #include 
    
    std::string str = "Hello World!";
    auto & f = std::use_facet>(std::locale());
    f.toupper(str.data(), str.data() + str.size());
    

    This will perform better than all the answers that use the global toupper function, and is presumably what boost::to_upper is doing underneath.

    This is because ::toupper has to look up the locale - because it might've been changed by a different thread - for every invocation, whereas here only the call to locale() has this penalty. And looking up the locale generally involves taking a lock.

    This also works with C++98 after you replace the auto, use of the new non-const str.data(), and add a space to break the template closing (">>" to "> >") like this:

    std::use_facet > & f = 
        std::use_facet >(std::locale());
    f.toupper(const_cast(str.data()), str.data() + str.size());
    

提交回复
热议问题