How to Convert std::string to Lower Case?
Last Updated :
21 Feb, 2024
A String is a data structure in C++ language used to store a set of characters. It can be a single word or can contain a sentence and also can contain large text. In this article, we will learn how to convert string to lowercase.
Example:
Input:
myString = "This Is Some StrIng"
Output:
myString = "this is some string"
Convert std::string to Lower Case in C++
To convert string to lowercase, we will use the function std::tolower() which converts any uppercase letter into a lowercase letter. If any lowercase letter is provided to it, the function keeps it as it is.
Approach
- We will go at each character by iterating through a string using a loop.
- We will then pass each character to the tolower() function which will return the lowercase of it.
- We will then append this returned character to the new string where the lowercase version will be stored.
C++ Program to Convert std::string to Lower Case
C++
#include <cctype>
#include <iostream>
#include <string>
using namespace std;
string convertToLowercase( const string& str)
{
string result = "" ;
for ( char ch : str) {
result += tolower (ch);
}
return result;
}
int main()
{
string input = "ABCDE" ;
cout << " string: " << input << endl;
string lowercase_str = convertToLowercase(input);
cout << "String in lowercase: " << lowercase_str
<< endl;
return 0;
}
|
Output
string: ABCDE
String in lowercase: abcde
Time complexity: O(N)
Space complexity: O(N)
Share your thoughts in the comments
Please Login to comment...