Thursday, May 19, 2011

String Madness

I read earlier today that Denis Ritchie (or Brian Kernigan, I get them mixed up) hates C++.

Now, why would anyone hate C++?

Oh wait, I had to do some case insensitive string compares today in C++. Let's see how to do it:
  1. Solution 1, download hundreds of megabytes of Boost - meh
  2. Comment #2, Unicode is broken, yea Unicode!
  3. Solution three:
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) {
while( n-- != 0 ) {
if( toupper(*s1) < toupper(*s2) ) return -1;
if( toupper(*s1) > toupper(*s2) ) return 1;
++s1; ++s2;
}
return 0;
}
static const char* find(const char* s, int n, char a) {
while( n-- > 0 && toupper(*s) != toupper(a) ) {
++s;
}
return s;
}
};

typedef std::basic_string<char, ci_char_traits> ci_string;

Muahahahahahaa! That's evil (Note: I handled all the freaky <> using Tcl, yea Tcl!). In case you're wondering:
string map "< {&lt;} > {&gt;}" $code


Solution 4, fall back to C. Thanks, that's great. Also, note it is different on different platforms, yea C. It also doesn't work on Unicode.

In Tcl?
string compare -nocase $str1 $str2


Works on most Unicode, but, hey Unicode is broken what do you want?

No comments: