C++ How to Convert String to Uppercase Easily
std::transform function with ::toupper, like this: std::transform(str.begin(), str.end(), str.begin(), ::toupper);.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(), [](unsigned char c){ return std::toupper(c); }); std::cout << str << std::endl; return 0; }
Dry Run
Let's trace the string "Hello" through the code.
Original string
str = "Hello"
Convert each character
H -> H, e -> E, l -> L, l -> L, o -> O
Final string
str = "HELLO"
| Original Char | Uppercase Char |
|---|---|
| H | H |
| e | E |
| l | L |
| l | L |
| o | O |
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: toupper function
The ::toupper function converts a single character to uppercase if it is lowercase; 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::toupper(static_cast<unsigned char>(c)); } std::cout << str << std::endl; return 0; }
#include <iostream> #include <string> #include <ranges> #include <cctype> int main() { std::string str = "Hello, World!"; // Using std::ranges::transform to convert to uppercase std::ranges::transform(str, str.begin(), [](unsigned char c){ return std::toupper(c); }); std::cout << str << std::endl; return 0; }
Complexity: O(n) time, O(1) space
Time Complexity
The algorithm processes each character once, so the time grows linearly with the string length.
Space Complexity
The conversion is done in-place, so no extra space proportional to input size is needed.
Which Approach is Fastest?
Using std::transform with ::toupper is efficient and concise; manual loops are similar in speed but less elegant.
| Approach | Time | Space | Best For |
|---|---|---|---|
| std::transform with ::toupper | O(n) | O(1) | Clean and efficient uppercase conversion |
| Manual loop with toupper | O(n) | O(1) | Simple and explicit control |
| C++20 std::ranges::transform | O(n) | O(1) | Modern C++ with ranges support |
std::transform with ::toupper for a clean and efficient uppercase conversion.cctype header or using toupper without casting to unsigned char can cause unexpected behavior.