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