In this C++ Tutorial we will explore the tolower() function, which can be used to convert a single character to it’s lowercase version. We will proceed to show exactly how one can convert an entire C++ String to lowercase, using the tolower() function.
C++ tolower() Syntax
The C++ tolower() function takes a single parameter, which is an integer representing the ascii value of a char. Don’t worry, you can still pass datatypes of type char. They are just integers in the end after all (Remember the ASCII table).
tolower(int ch);
Example# 1 (Converting a Char)
In this example, we will take a look at how to convert some simple characters in C++ to lowercase using the tolower() function. You can pass both lowercase and uppercase characters into it.
int main() {
char a = 'A';
char b = 'B';
char c = 'C';
cout << tolower(a) << endl;
cout << tolower(b) << endl;
cout << tolower(c) << endl;
}
The output:
97
98
99
If you want the output to be in the form of actual characters, you can use typecasting, and convert the int value to its’ character representation.
int main() {
char a = 'A';
char b = 'B';
char c = 'C';
cout << (char) tolower(a) << endl;
cout << (char) tolower(b) << endl;
cout << (char) tolower(c) << endl;
}
The output:
a
b
c
Alternatively, you can just store the int value returned into a char variable, which will print out an actual character if you try printing it.
Example# 2 (Converting a String)
In this example we will take a String with Uppercase characters and convert it to a Lowercase string.
The tolower() function does not work on strings natively, but remember that a String is merely a collection of characters. Hence, with the following approach, where iterate over each individual character in a String, we can convert it to lowercase.
#include <iostream>
#include <string>
using namespace std;
int main() {
string var = "HELLO WORLD";
for (int i = 0; i < var.length(); i++) {
var[i] = tolower(var[i]);
}
cout << "New String: " << var << endl;
}
The output:
New String: hello world
Alternatives
There are other alternatives for converting a C++ string to Lowercase. You can find a complete C++ String to Lowercase tutorial + examples by following this link.
This marks the end of the C++ tolower(), Converting String to Lowercase Tutorial. Any suggestions or contributions for CodersLegacy are more than welcome. Questions regarding the tutorial content will be asked in the comments section below.
thank bro
fesfnsnkef