Re: C++ - how to convert string to uppercase/lowercase
On Dec 18, 12:32 am, Jeff Schwab <j...@schwabcenter.com> wrote:
Sam wrote:
sean_in_rale...@yahoo.com writes:
On Dec 17, 12:29 pm, Michal <rabbi...@tenbit.pl> 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?
Here's the STL-ish way.
//////
#include <cctype>
#include <algorithm>
#include <string>
int my_toupper(int c)
{
return toupper(c);
}
int
main(int argc, char **argv)
{
using namespace std;
string s = "hello world";
transform(s.begin(), s.end(), s.begin(), my_toupper);
}
////
That's not very STL-ish.
You have to create my_toupper (or use a cast) due to a C++
wart.
No you don't.
std::transform(s.begin(), s.end(), s.begin(),
std::ptr_fun(toupper));
works just fine. /That/ is the STL-ish way.
What does using std::ptr_fun acheve? toupper is still
ambiguous, and there's no way for template type deduction to
work.
The non-wart in question is also easily avoided by qualifying
the name as ::toupper.
Only if you include <ctype.h>, rather than <cctype>. (According
to the current standard, if you include <cctype>, and the
compiler finds a ::toupper, the implementation isn't conform.
Most aren't in this regard, however.)
And of course, none of this addresses the fact that you can't
call ::toupper with a char without invoking undefined behavior.
The minimum STL solution would use something like:
struct ToUpper
{
char operator()( char ch ) const
{
return toupper( static_cast< unsigned char >( ch ) ) ;
}
} ;
A better solution would use a functional object which contained
a reference to an std::ctype< char >, and called toupper on it.
And while arguably, something like this really belongs in the
standard library, in practice, it doesn't really work either.
Especially if you're using Unicode (UTF-8):-).
--
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