Case-Insensitive

/* 

ci_string s( "AbCdE" ); 

// case insensitive
//
assert( s == "abcde" );
assert( s == "ABCDE" );

// still case-preserving, of course
//
assert( strcmp( s.c_str(), "AbCdE" ) == 0 );
assert( strcmp( s.c_str(), "abcde" ) != 0 );

// the char_traits defines how characters interact-and compare!
// the char_traits eq(), lt(), compare(), find(). 

*/

#include <iostream>
#include <string>

using namespace std;;


// just inherit all the other functions that we don't need to replace
struct ci_char_traits : public char_traits<char> 
{
	static bool eq(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 ); }
	
	// if available on your platform, otherwise you can roll your own
	static const char* find(const char* s, int n, char a)
	{
		while(n-- > 0 && toupper(*s) != toupper(a))
		{
			++s;
		}
		return n >= 0 ? s : 0;
	}
};


// char_traits control the a string's characters
typedef basic_string<char, ci_char_traits> ci_string;

int main()
{
	ci_string	a("aaa");
	cout << a.c_str() << endl;  
	// typedef basic_ostream<char, char_traits<char> > ostream;

// 	string b;
// 	string c = a + b;
// 
// 	cout << b;
}
學習char_traits

發佈了42 篇原創文章 · 獲贊 0 · 訪問量 8601
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章