IS THERE A FUNCTION FOR CONVERTING A STRING TO UPPERCASE

OK, Here is the problem, I need to know is there is a string function that can convert the whole string into uppercase instead of the function toupper(char) which does it character by character.
closed account (o1vk4iN6)
If you know it's all characters and no symbols you can simply do char c; c = (c & ~(0x20)) for each character. Which will remove the bit that makes a character lower case, either way you need to go through each character.
Last edited on
toupper(): http://www.cplusplus.com/reference/clibrary/cctype/toupper/

It works in a per-character basis, so one usually applies it with a std::transform().
STL solution:

1
2
std::string str = "hello world";
std::transform(str.begin(), str.end(), str.begin(), std::ptr_fun(::toupper));

Boost solution:
http://www.boost.org/doc/libs/1_48_0/doc/html/string_algo/usage.html#id3115204
I've tried using the function toupper() and i think im doing something wrong because instead of it returning uppercase characters, it returns integers. whats causing this?
whats causing this?


You've instructed your compiler to treat them as integer values. Let's see the code.
This might make the difference:

 
std::transform( s.begin(), s.end(), s.begin(), std::ptr_fun <int, int> ( std::toupper ) );

I have been informed that, for some reason, ptr_fun<>() has been deprecated in C++11 -- which I am not sure I like because it makes for less-readable code IMHO:

 
std::transform( s.begin(), s.end(), s.begin(), (int(*)(int))( std::toupper )

Alas.
link: http://www.cplusplus.com/forum/general/56945/
Last edited on
Right, as of n3242, the last freely available C++ working draft, ptr_fun is now deprecated.
For truly C++11 code you would write:

1
2
std::transform(s.begin(), s.end(), s.begin(), std::function<char (char)>(::toupper));
// compiled with 'g++ -std=c++0x test.cpp' under linux 
Last edited on
Case insensitive compare:
1
2
3
4
5
6
7
8
9
bool ci_compare(const std::wstring& l, const std::wstring& r)
{
	const std::locale loc("");// system locale
	std::pair< std::wstring::const_iterator, std::wstring::const_iterator > result;
	result = std::mismatch(l.begin(), l.end(), r.begin(), 
	[&loc] (std::wstring::value_type chl, std::wstring::value_type chr)
	{ return std::toupper(chl, loc) == std::toupper(chr, loc); } );
	return l.end() == result.first;
}
Last edited on
@mtrenkmann
Ooh, I like std::function<>!

@morando
I like the idea of lambdas, but I think we now have a valid argument for being more obtuse than C...
With C++11, I wouldn't take the trouble of using std::transform() for this.

1
2
std::string str = "whatever" ;
for( auto& c :  str ) c = std::toupper(c) ;
Yay!
Topic archived. No new replies allowed.