Convert first letter of a string to uppercase in C++
This post will discuss how to convert the first letter of a string to uppercase in C++.
1. Using toupper() function
The standard solution to convert a lowercase letter to uppercase is using the toupper() function from <cctype> header. The idea is to extract the first letter from the given string, and convert it to uppercase. This works in-place, since strings are mutable in C++.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
#include <iostream> #include <string> #include <cctype> void toUpper(std::string &str) { if (str.length() == 0) { return; } str[0] = std::toupper(str[0]); } int main() { std::string str = "tech"; toUpper(str); std::cout << str << std::endl; // Tech return 0; } |
2. Using std::transform
To capitalize the first letter and lowercase the rest, use the std::transform from the standard library. The idea is to lowercase the complete string and then convert the first letter to uppercase.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
#include <iostream> #include <string> #include <cctype> #include <algorithm> void toUpper(std::string &str) { if (str.length() == 0) { return; } std::transform(std::begin(str), std::end(str), std::begin(str), [](char const &c) { return std::tolower(c); }); str[0] = std::toupper(str[0]); } int main() { std::string str = "tEcH"; toUpper(str); std::cout << str << std::endl; // Tech return 0; } |
We can further shorten the above code with tolower from the global namespace which can be directly referenced with a name, as shown below:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
#include <iostream> #include <string> #include <cctype> #include <algorithm> void toUpper(std::string &str) { if (str.length() == 0) { return; } std::transform(str.begin(), str.end(), str.begin(), ::tolower); str[0] = std::toupper(str[0]); } int main() { std::string str = "tech"; toUpper(str); std::cout << str << std::endl; // Tech return 0; } |
That’s all about converting the first letter of a string to uppercase in C++.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)