I wrote a templated version that works with any string :
#include <type_traits> // std::decay #include <ctype.h> // std::toupper & std::tolower template <class T = void> struct farg_t { using type = T; }; template <template<typename ...> class T1, class T2> struct farg_t <T1<T2>> { using type = T2*; }; //--------------- template<class T, class T2 = typename std::decay< typename farg_t<T>::type >::type> void ToUpper(T& str) { T2 t = &str[0]; for (; *t; ++t) *t = std::toupper(*t); } template<class T, class T2 = typename std::decay< typename farg_t<T>::type >::type> void Tolower(T& str) { T2 t = &str[0]; for (; *t; ++t) *t = std::tolower(*t); }
Tested with gcc compiler:
#include <iostream> #include "upove_code.h" int main() { std::string str1 = "hEllo "; char str2 [] = "wOrld"; ToUpper(str1); ToUpper(str2); std::cout << str1 << str2 << '\n'; Tolower(str1); Tolower(str2); std::cout << str1 << str2 << '\n'; return 0; }
output:
>HELLO WORLD > >hello world
tolower()doesn't work 100% of the time. Lowercase/uppercase operations only apply to characters, and std::string is essentially an array of bytes, not characters. Plaintoloweris nice for ASCII string, but it will not lowercase a latin-1 or utf-8 string correctly. You must know string's encoding and probably decode it before you can lowercase its characters.