C++ Code Snippet - In-Place and String-Copy Uppercase/Lowercase Conversion of STL Strings
Posted on 2007-06-02 13:22 by Timo Bingmann at Permlink with 2 Comments. Tags: #c++ #code-snippet
This post completes the small C++ function collection of simple STL string manipulations. The following code snippet shows simple locale-unware uppercase and lowercase conversion functions using tolower
and toupper
. Nothing revolutionary; I'm just misusing this weblog as a code-paste dump for reuseable code.
Sometimes it is better to have a case-insensitive string class. More about ci_string
can be found at Guru of the Week (GotW) #29: Case-Insensitive Strings.
#include <string> #include <cctype> // functionals for std::transform with correct signature static inline char string_toupper_functional(char c) { return std::toupper(c); } static inline char string_tolower_functional(char c) { return std::tolower(c); } static inline void string_upper_inplace(std::string &str) { std::transform(str.begin(), str.end(), str.begin(), string_toupper_functional); } static inline void string_lower_inplace(std::string &str) { std::transform(str.begin(), str.end(), str.begin(), string_tolower_functional); } static inline std::string string_upper(const std::string &str) { std::string strcopy(str.size(), 0); std::transform(str.begin(), str.end(), strcopy.begin(), string_toupper_functional); return strcopy; } static inline std::string string_lower(const std::string &str) { std::string strcopy(str.size(), 0); std::transform(str.begin(), str.end(), strcopy.begin(), string_tolower_functional); return strcopy; }
#include <assert.h> // Test the functions above int main() { // string-copy functions assert( string_upper(" aBc ") == " ABC " ); assert( string_lower(" AbCdEfG ") == " abcdefg " ); // in-place functions std::string str1 = " aBc "; std::string str2 = "AbCdEfGh "; string_upper_inplace(str1); string_lower_inplace(str2); assert( str1 == " ABC " ); assert( str2 == "abcdefgh " ); return 0; }
Hi Timo, Thanks for your example of Flex Bison C++ Unless I'm wrong what you provide in this section is already implemeted in : Boost String Algorithms Library cheers François