how do you change a string from uppercase to lowercase

I wanted to know how to change a string from uppercase to lower case without a loop. I've been trying to look for a solution online but cant find one. I thought this would work but I keep getting a ‘std::string’ has no member named ‘tolower’ error. please help


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
  string normalize(string s)
 11 {
 12 
 13  string target(s.tolower());
 14 
 15 
 16 
 17 return target;
 18 }
 19 
 20 
 21 int main()
 22 {
 23 
 24 
 25 
 26   string s = "HELLOW WORLD";
 27 cout<<normalize(s)<<endl;
 28 
 29 return 0;
 30 }
The tolower function applies to character arrays, not strings. Now, if you want to use tolower with a string, you will need to use std::transform, which is in the algorithm library. Specifically, it would be written as thus:
1
2
3
4
5
std::string normalize (string s)
{
    std::transform(s.begin(), s.end(), s.begin(), ::tolower);
    return s;
}


Note that you must #include <algorithm> to use transform.
Last edited on
Thanks for the help it worked.
And if you are not allowed to use transform you can loop through each character in the string. Also if you read on the tolower function it takes a parameter of a character and it is not a member function of the string class but from the cctype library. http://www.cplusplus.com/reference/cctype/tolower/?kw=tolower

So the way to do it without the algorithm would be:
1
2
3
4
for( int i = 0; i < SIZE_OF_STRING; ++i )
{
    some_string[i] = tolower(some_string[i];
}

or you can use iterators I suppose.
Topic archived. No new replies allowed.