Mar 27, 2010

Doing a case insensitive find in C++

Surprisingly the standard C++ library doesn’t provide support for doing a case insensitive search on a string. The boost library might and there is almost certainly a traits class out there that you could use for this but if like me you’re in the embedded world and want a very fast and lightweight solution, you can use the ostringstream class and the uppercase formatter from <ios> for a quick-fix.  Doing it this way you can avoid calling the C library uppercase on every character in the string.  So in addition to the case insensitive find you get a nice ToUpper() method for strings. Sure wish C++  extension methods were here and I could make these look like part of the native string class.

image

FindInsensitive() just converts both strings to uppercase and then uses the normal find() member function.

About Me

My photo
Tod Gentille (@todgentille) is now a Curriculum Director for Pluralsight. He's been programming professionally since well before you were born and was a software consultant for most of his career. He's also a father, husband, drummer, and windsurfer. He wants to be a guitar player but he just hasn't got the chops for it.