Convert a String In C++ To Upper Case

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

    struct convert {
       void operator()(char& c) { c = toupper((unsigned char)c); }
    };
    
    // ... 
    string uc_str;
    for_each(uc_str.begin(), uc_str.end(), convert());
    

    Note: A couple of problems with the top solution:

    21.5 Null-terminated sequence utilities

    The contents of these headers shall be the same as the Standard C Library headers , , , , and [...]

    • Which means that the cctype members may well be macros not suitable for direct consumption in standard algorithms.

    • Another problem with the same example is that it does not cast the argument or verify that this is non-negative; this is especially dangerous for systems where plain char is signed. (The reason being: if this is implemented as a macro it will probably use a lookup table and your argument indexes into that table. A negative index will give you UB.)

提交回复
热议问题