Re: C++ - how to convert string to uppercase/lowercase
On Dec 17, 10:34 pm, Kai-Uwe Bux <jkherci...@gmx.net> wrote:
Michal wrote:
I looked through ANSI/ISO C++ standard string, and I did not
find any function from string class that would do so. Did I
overlooked something or it is so?
Maybe something like:
#include <locale>
#include <string>
template < typename Char, typename Traits >
std::basic_string< Char, Traits > &
to_lower ( std::basic_string< Char, Traits > & str,
std::locale loc = std::locale() ) {
typedef std::basic_string< Char, Traits > string;
typedef std::ctype< Char > char_type;
char_type const * the_type_ptr = &std::use_facet< char_type >( loc )=
;
for ( typename string::size_type i = 0; i < str.size(); ++i ) {
str[i] = the_type_ptr->tolower( str[i] );
}
return ( str );
}
Why not?
template< typename Char, typename Traits >
std::basic_string< Char, Traits >
toLower(
std::basic_string< Char, Traits > const&
in,
std::locale loc = std::locale() )
{
std::basic_string< Char, Traits >
result( in ) ;
std::use_facet< std::ctype< Char > >( loc )
.toupper( &result[ 0 ], &result[ 0 ] + result.size() ) ;
return result ;
}
Technically, this isn't guaranteed in the current standard, but
it works with all known implementations, and will be guaranteed
in the next.
Of course, it still doesn't work for something like "er isst und
a=DF in hohem Ma=DFe", which should return "ER ISST UND ASS IN HOHEM
MASZE" (and the tolower equivalent won't get you back to the
original, either).
--
James Kanze (GABI Software) email:james.kanze@gmail.com
Conseils en informatique orient=E9e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S=E9mard, 78210 St.-Cyr-l'=C9cole, France, +33 (0)1 30 23 00 34