1 |
#ifndef __STRING_NOCASE_H__ |
2 |
#define __STRING_NOCASE_H__ |
3 |
|
4 |
#include <string> |
5 |
#include <iostream> |
6 |
#include <cctype> |
7 |
|
8 |
// case insensitive character traits |
9 |
// inherited copy (preserves case), |
10 |
// case insensitive comparison, search |
11 |
struct traits_nocase : std::char_traits<char> |
12 |
{ |
13 |
static bool eq( const char& c1, const char& c2 ) |
14 |
{ return toupper(c1) == toupper(c2) ; } |
15 |
static bool lt( const char& c1, const char& c2 ) |
16 |
{ return toupper(c1) < toupper(c2) ; } |
17 |
static int compare( const char* s1, const char* s2, size_t N ) |
18 |
{ |
19 |
return strncasecmp( s1, s2, N ) ; // posix |
20 |
// mirosoft C++ - use _strnicmp instead |
21 |
} |
22 |
static const char* find( const char* s, size_t N, const char& a ) |
23 |
{ |
24 |
for( size_t i=0 ; i<N ; ++i ) |
25 |
if( toupper(s[i]) == toupper(a) ) return s+i ; |
26 |
return 0 ; |
27 |
} |
28 |
static bool eq_int_type ( const int_type& c1, const int_type& c2 ) |
29 |
{ return toupper(c1) == toupper(c2) ; } |
30 |
}; |
31 |
|
32 |
// string preserves case; comparisons are case insensitive |
33 |
typedef std::basic_string< char, traits_nocase > string_nocase ; |
34 |
|
35 |
// make string_nocase work like a std::string |
36 |
// with streams using std::char_traits |
37 |
// std::basic_istream< char, std::char_traits<char> > (std::istream) and |
38 |
// std::basic_ostream< char, std::char_traits<char> > (std::ostream) |
39 |
inline std::ostream& operator<< ( std::ostream& stm, const string_nocase& str ) |
40 |
{ return stm << reinterpret_cast<const std::string&>(str) ; } |
41 |
|
42 |
inline std::istream& operator>> ( std::istream& stm, string_nocase& str ) |
43 |
{ |
44 |
std::string s ; stm >> s ; |
45 |
if(stm) str.assign(s.begin(),s.end()) ; |
46 |
return stm ; |
47 |
} |
48 |
|
49 |
inline std::istream& getline( std::istream& stm, string_nocase& str ) |
50 |
{ |
51 |
std::string s ; std::getline(stm,s) ; |
52 |
if(stm) str.assign(s.begin(),s.end()) ; |
53 |
return stm ; |
54 |
} |
55 |
|
56 |
#endif // __STRING_NOCASE_H__ |