Exceptional C++

【Exceptional C++(2)】不区分大小写的strin

2018-01-26  本文已影响24人  downdemo

问题

ci_string s("AbCdE");
assert(s == "abcde");
assert(s == "ABCDE");
assert(strcmp(s.c_str(), "AbCdE") == 0); // c_str()返回C字符串指针,const char* c_str()
assert(strcmp(s.c_str(), "abcde") != 0);

解答

typedef basic_string<char> string;
template<class charT,
    class traits = char_traits<charT>,
    class Allocator<charT> >
class basic_string;
struct ci_char_traits : public char_traits<char>
{
    static bool eq( char c1, char c2 )
    {
        return toupper(c1) == toupper(c2);
    }
    static bool ne( char c1, char c2 )
    {
        return toupper(c1) != toupper(c2);
    }
    static bool lt(char c1, char c2)
    {
        return toupper(c1) < toupper(c2);
    }
    static int compare( const char * s1, const char * s2, size_t n )
    {
        return memicmp(s1, s2, n); // 如果编译器没提供得自己实现
    }
    static const char* find( const char* s, int n, char a )
    {
        while( n-- > 0 && toupper(*s) != toupper(a))
        {
            ++s;
        }
        return n >= 0 ? s : 0;
    }
};
// 最后把它们合在一起
typedef basic_string<char, ci_char_traits> ci_string;
template<class char, class traits, class Allocator>
basic_ostream<charT, traits>&
operator<<(basic_ostream<charT, traits>& os,
    const basic_string<charT, traits, Allocator>& str)
ci_string s = "abc";
cout << s.c_str() << endl;
上一篇下一篇

猜你喜欢

热点阅读