Converting String Case in C++
What's the best way to convert all characters in a std::string
to uppercase or lowercase?
Converting the case of characters in a std::string
is a common operation in text processing. C++ provides functions in the <algorithm>
and <cctype>
headers to accomplish this task efficiently.
Here's how you can convert a string to uppercase or lowercase:
#include <iostream>
#include <string>
#include <algorithm>
#include <cctype>
int main() {
std::string text{"Hello, World!"};
// Convert to uppercase
std::string uppercase{text};
std::ranges::transform(
uppercase, uppercase.begin(),
[](unsigned char c) {
return std::toupper(c);
});
// Convert to lowercase
std::string lowercase{text};
std::ranges::transform(
lowercase, lowercase.begin(),
[](unsigned char c) {
return std::tolower(c);
});
std::cout << "Original: " << text << '\n';
std::cout << "Uppercase: " << uppercase << '\n';
std::cout << "Lowercase: " << lowercase << '\n';
}
Original: Hello, World!
Uppercase: HELLO, WORLD!
Lowercase: hello, world!
Let's break down the approach:
- We use
std::ranges::transform()
(C++20) to apply a transformation to each character. - The lambda function
[](unsigned char c){ return std::toupper(c); }
is used to convert each character to uppercase. We useunsigned char
to avoid undefined behavior with negative char values. std::toupper()
andstd::tolower()
from<cctype>
are used for the actual character conversion.
If you're using a pre-C++20 compiler, you can use std::transform()
instead:
std::transform(
text.begin(), text.end(), text.begin(),
[](unsigned char c) {
return std::toupper(c);
}
);
Note that this method works well for ASCII characters, but it may not handle Unicode characters correctly. For proper Unicode support, you might need to use a library like ICU (International Components for Unicode).
Also, be aware that these functions modify the string in-place. If you need to preserve the original string, make a copy before transforming, as shown in the example.
Remember, when working with std::string
, it's often more efficient to modify the string in-place rather than creating a new string for each operation. This approach minimizes memory allocations and copies, leading to better performance, especially for longer strings or frequent operations.
A Deeper Look at the std::string
Class
A detailed guide to std::string
, covering the most essential methods and operators