Ray's playground

 

Strings(Chapter 1 of Thinking in C++ Vol 2)

ichar_traits.h
 1 #ifndef ICHAR_TRAITS_H
 2 #define ICHAR_TRAITS_H
 3 #include <string>
 4 #include <cctype>
 5 
 6 struct ichar_traits : std::char_traits<char>
 7 {
 8     static bool eq(char c1st, char c2nd)
 9     {
10         return std::toupper(c1st) == std::toupper(c2nd);
11     }
12 
13     static bool ne(char c1st, char c2nd)
14     {
15         return std::toupper(c1st) != std::toupper(c2nd);
16     }
17 
18     static bool lt(char c1st, char c2nd)
19     {
20         return std::toupper(c1st) < std::toupper(c2nd);
21     }
22 
23     static int compare(const char* str1, const char* str2, size_t n)
24     {
25         for(int i=0; i<n; i++)
26         {
27             if(std::tolower(*str1) > std::tolower(*str2))
28             {
29                 return 1;
30             }
31             if(std::tolower(*str1) < std::tolower(*str2))
32             {
33                 return -1;
34             }
35 
36             if(*str1 == 0 || *str2 == 0)
37             {
38                 return 0;
39             }
40             str1++;
41             str2++;
42         }    
43         return 0;
44     }
45 
46     static const char* find(const char* s1, int n, char c)
47     {
48         while(n-- > 0 && std::toupper(*s1) != std::toupper(c))
49         {
50             s1++;
51         }
52         return s1;
53     }
54 };
55 
56 #endif

 

Main
 1 #include "ichar_traits.h"
 2 #include <string>
 3 #include <iostream>
 4 using namespace std;
 5 
 6 typedef basic_string<char, ichar_traits, allocator<char> > istring;
 7 
 8 int main()
 9 {
10     istring first = "tHis";
11     istring second = "ThIs";
12     cout << first.compare(second) << endl;
13     cin.get();
14 } 

posted on 2010-12-11 15:04  Ray Z  阅读(196)  评论(0编辑  收藏  举报

导航