OneBite.Dev - Coding blog in a bite size

Convert A String To Lowercase In C++

Code snippet for how to Convert A String To Lowercase In C++ with sample and detail explanation

Converting a string to lowercase is a common task in many programming activities. This article provides a simple tutorial on how to convert a string to lowercase in C++ programming language. It explains the process with a code snippet and a detailed explanation.

Code Snippet to Convert a String to Lowercase in C++

The following is a simple example of how to convert a string to lowercase in C++:

#include <algorithm>
#include <string>
using namespace std;

int main() {
    string str = "HELLO WORLD";
    transform(str.begin(), str.end(), str.begin(), ::tolower);
    cout << str << endl;  // "hello world"
    return 0;
}

The example shows a simple way to convert the string “HELLO WORLD” to lowercase “hello world”.

Code Explanation for Converting a String to Lowercase in C++

The structure of the code is quite simple. First of all, the necessary libraries to carry out the task are included: <algorithm> and <string>. The algorithm library is included to use the transform function, while the string library is included for string manipulation features like string methods and operators.

The main() function is the entry point of the code. Inside the main() function, a string str is defined with the value “HELLO WORLD”.

Then comes the transform() function from the algorithm library, which is designed to apply a function to a range of elements. In this context, the transform() function applies the ::tolower function to each character in the string. The ::tolower function, as its name suggests, converts a character to lowercase.

Here’s a breakdown of the transform() function parameters:

  • str.begin() specifies the beginning of the range, or the first element of the string.
  • str.end() specifies the end of the range, or one past the last element of the string.
  • str.begin() again, specifies where to store the converted characters, in this case, back to the original elements.
  • ::tolower is the operation to apply to each character in the string. This function takes each character of the string and converts it to lowercase.

Finally, the converted string is printed to the standard output with cout. After the string has been transformed, it is printed out as “hello world”.

In conclusion, with the help of transform function and tolower operation from the algorithm and cctype libraries respectively, we can easily convert all of the alphabetic characters in a string to lowercase in a compact and efficient manner.

c-plus-plus