Convert a String In C++ To Upper Case

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

    If you are only concerned with 8 bit characters (which all other answers except Milan Babuškov assume as well) you can get the fastest speed by generating a look-up table at compile time using metaprogramming. On ideone.com this runs 7x faster than the library function and 3x faster than a hand written version (http://ideone.com/sb1Rup). It is also customizeable through traits with no slow down.

    template
    struct IntVector{
    using Type = IntVector;
    };
    
    template
    struct PushFront;
    template
    struct PushFront,I_New> : IntVector{};
    
    template>
    struct Iota : Iota< I_Size-1, typename PushFront::Type> {};
    template
    struct Iota<0,T_Vector> : T_Vector{};
    
    template
    struct ToUpperTraits {
        enum { value = (C_In >= 'a' && C_In <='z') ? C_In - ('a'-'A'):C_In };
    };
    
    template
    struct TableToUpper;
    template
    struct TableToUpper>{
        static char at(const char in){
            static const char table[] = {ToUpperTraits::value...};
            return table[in];
        }
    };
    
    int tableToUpper(const char c){
        using Table = TableToUpper::Type>;
        return Table::at(c);
    }
    

    with use case:

    std::transform(in.begin(),in.end(),out.begin(),tableToUpper);
    

    For an in depth (many page) decription of how it works allow me to shamelessly plug my blog: http://metaporky.blogspot.de/2014/07/part-4-generating-look-up-tables-at.html

提交回复
热议问题