Look at the function signatures, they have different side effects.
strlower makes a
copy of the string you give it, changes case, and returns the copy. Well, a copy of the copy....
Anywho,
strlwr() does what your original function does, and changes the string you pass it in-place.
Hence:
1 2 3
|
string s = "Hello world!";
strlwr( s );
cout << s << endl;
|
works as you would expect. But:
1 2 3
|
string s = "Hello world!";
strlower( s );
cout << s << endl;
|
does not, since
s was not modified (and the lowercased string returned from the function was thrown away). Fix it thus:
1 2 3
|
string s = "Hello world!";
s = strlower( s );
cout << s << endl;
|
Now it works, because you copy the result of the lowercased string into
s.
The nice part about the
strlower() version is that you can say things like:
|
cout << strlower( "Hello world!" ) << endl;
|
Whereas you cannot with the
strlwr() version.
Looking at it again, I suppose it might have been smarter of me to just name the functions identically, so the compiler can choose the proper overload for you.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
|
#ifndef STRLOWER_HPP
#define STRLOWER_HPP
#include <algorithm>
#include <cctype>
#include <functional>
#include <string>
inline std::string& strlower( std::string& s )
{
std::transform( s.begin(), s.end(), s.begin(), std::ptr_fun <int, int> ( std::tolower ) );
return s;
}
inline std::string strlower( const std::string& s )
{
std::string result( s );
return strlower( result );
}
#endif
|
Hope this helps.