How to Convert std::string to Lower Case?
Last Updated :
04 Nov, 2024
Converting string to lower case means all the alphabets present in the string should be in lower case. In this article, we will learn how to convert the std::string to lowercase in C++.
Examples
Input: s = "GEEKS for GEEKS"
Output: geeks for geeks
Explanation: All characters of s are converted to lowercase.
Input: s = "HelLO WoRld"
Output: hello world
Explanation: All characters of s are converted to lowercase.
Following are the 3 different methods to convert the std::string (C++ Style Strings) to lower case in C++:
We can convert the given std::string to lower case using std::transform() with std::tolower() method. This method applies the given tolower() function to each of the character converting it to lowercase if its not.
Syntax
std::transform(s.begin(), s.end(), s.begin(), ::tolower);
where, s is the string to be converted.
Example
C++
// C++ Program to convert the std::string to
// lower case using std::transform()
#include <bits/stdc++.h>
using namespace std;
int main() {
string s = "GEEKS for GEEKS";
// Converting the std::string to lower case
// using std::transform()
transform(s.begin(), s.end(), s.begin(),
::tolower);
cout << s;
return 0;
}
Time Complexity: O(n), where n is the length of string.
Auxiliary Space: O(1)
Using std::for_each()
We can also convert the given std::string to lower case using std::for_each loop with lambda function that convert the given character to its lower case using tolower() function.
Example
C++
// C++ Program to convert the std::string to
// lower case using std::for_each loop with
// lambda expression
#include <bits/stdc++.h>
using namespace std;
int main() {
string s = "GEEKS for GEEKS";
// Converting the std::string to lower case
for_each(s.begin(), s.end(), [](char& c) {
c = tolower(c);
});
cout << s;
return 0;
}
Time Complexity: O(n), where n is the length of string.
Auxiliary Space: O(1)
Manually Using ASCII Values
C++ uses ASCII charset in which characters are represented by 7-bit numbers called ASCII numbers. Also, lowercase alphabet for corresponding uppercase alphabet always differs by 32. So, we can use this property to convert each character of std::string to lowercase one by one by adding 32 to the uppercase character.
Example
C++
// C++ program to convert std::string to lowercase
// manually using ASCII values
#include <bits/stdc++.h>
using namespace std;
void toLowerCase(string& s) {
// Manual converting each character to lowercase
// using ASCII values
for (char &c : s) {
if (c >= 'A' && c <= 'Z') {
// Convert uppercase to lowercase
// by adding 32
c += 32;
}
}
}
int main() {
string s = "GEEKS for GEEKS";
// Converting s to lowercase
toLowerCase(s);
cout << s;
return 0;
}
Time Complexity: O(n), where n is the length of string.
Auxiliary Space: O(1)