::TOUPPER
TOUPPER
Converting a string to uppercase with transform() and ::toupper requires a few specific headers. The <algorithm> header provides access to the std::transform() function, which applies an operation across a sequence of elements. The <cctype> header supplies the global ::toupper function used to convert characters to uppercase. Finally, the <string> header is needed when working with std:string objects as the source or destination of the transformation. Together, these headers ensure the code is portable, standards-compliant, and avoids relying on compiler-specific behavior.
std::transform(str.begin(), str.end(), str.begin(), ::toupper)
* str.begin(), // The beginning of the range (start of the string)
str.end(), // The end of the range (end of the string)
str.begin(), // The destination where transformed elements are stored (same string)
::toupper // The transformation applied to each element (convert to uppercase)
transform(
variableName.begin(), // 1. Start of the range
variableName.end(), // 2. End of the range
variableName.begin(), // 3. Destination start (same as source, so changes in place)
::toupper // 4. Operation to apply (convert each char to uppercase)
);
* variableName.begin() – Iterator pointing to the first character of the string.
* variableName.end() – Iterator pointing just past the last character.
* variableName.begin() (again) – The place where transformed characters will be written.
- Since this is the same as the input range, it modifies the string in place.
- If a different destination is specified, then the original isn't modified
* ::toupper – A function from <cctype> that converts a single char to uppercase.
- The :: means “use the global scope” to make sure we call the C library toupper instead of something else.
VERSION 1: MODIFICATION IN-PLACE
#include <iostream> // For input and output
#include <algorithm> // For transform
#include <cctype> // supplies the global ::toupper
#include <string> // required for std::string objects
using namespace std;
int main()
{
string str = "coding is fun"; // Original string
transform(str.begin(), str.end(), str.begin(), ::toupper); // Convert to uppercase
cout << "Uppercase String: " << str << endl; // Display result
return 0;
}
VERSION 2: ORIGINAL NOT MODIFIED
#include <iostream>
#include <algorithm>
#include <string>
#include <cctype>
using namespace std;
int main()
{
string text = "Hello"; // original data
string result(text.size(), '\0'); // separate container for results
// Transform into uppercase but write into `result`, not `text`
transform(text.begin(), text.end(), result.begin(), ::toupper);
// Print original
cout << "Original: " << text << endl; // Hello
// Print transformed
cout << "Transformed: " << result << endl; // HELLO
return 0;
}
Last updated