C++ How to Convert String to Lowercase Easily
std::transform with tolower like this: std::transform(str.begin(), str.end(), str.begin(), ::tolower);Examples
How to Think About It
Algorithm
Code
#include <iostream> #include <string> #include <algorithm> #include <cctype> int main() { std::string str = "Hello World!"; std::transform(str.begin(), str.end(), str.begin(), ::tolower); std::cout << str << std::endl; return 0; }
Dry Run
Let's trace the string "Hello World!" through the code
Initial string
str = "Hello World!"
Convert each character
H -> h, e -> e, l -> l, l -> l, o -> o, ' ' -> ' ', W -> w, o -> o, r -> r, l -> l, d -> d, ! -> !
Final string
str = "hello world!"
| Original Char | Converted Char |
|---|---|
| H | h |
| e | e |
| l | l |
| l | l |
| o | o |
| W | w |
| o | o |
| r | r |
| l | l |
| d | d |
| ! | ! |
Why This Works
Step 1: Using std::transform
The std::transform function applies a given operation to each element in a range, here each character in the string.
Step 2: Using ::tolower
The ::tolower function converts a single character to lowercase if it is uppercase; otherwise, it returns the character unchanged.
Step 3: In-place modification
By passing the string's begin iterator as both input and output, the string is modified directly without extra memory.
Alternative Approaches
#include <iostream> #include <string> #include <cctype> int main() { std::string str = "Hello World!"; for (char &c : str) { c = std::tolower(c); } std::cout << str << std::endl; return 0; }
#include <iostream> #include <string> #include <algorithm> #include <cctype> int main() { std::string str = "Hello World!"; std::string lower_str; lower_str.resize(str.size()); std::transform(str.begin(), str.end(), lower_str.begin(), ::tolower); std::cout << lower_str << std::endl; return 0; }
Complexity: O(n) time, O(1) space
Time Complexity
The code processes each character once, so time grows linearly with string length.
Space Complexity
The conversion is done in-place, so no extra space beyond the input string is needed.
Which Approach is Fastest?
Using std::transform in-place is generally fastest and most readable; manual loops are similar but more verbose; creating a new string uses extra memory.
| Approach | Time | Space | Best For |
|---|---|---|---|
| std::transform in-place | O(n) | O(1) | Efficient and clean lowercase conversion |
| Manual loop with tolower | O(n) | O(1) | Simple and explicit control |
| std::transform to new string | O(n) | O(n) | Preserving original string |
std::transform with ::tolower for a clean and efficient lowercase conversion.<cctype> or using tolower without std:: or :: can cause errors.