How to convert string to lowercase in C++?

by lue.lemke , in category: C/C++ , 2 years ago

How to convert string to lowercase in C++?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

Member

by dasia , 2 years ago

@lue.lemke you can use for_each() loop to go through all characters in C++ and make it lowercase, code as an example:


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
#include <string>
#include <algorithm>
#include <iostream>

int main() {
    std::string str = "TEST String.";

    // convert string to lowercase
    std::for_each(str.begin(), str.end(), [](char & c){
        c = ::tolower(c);
    });

    // Output: test string.
    std::cout << str;

    return 0;
}

Member

by rollin , a year ago

@lue.lemke 

To convert a string to lowercase in C++, you can use the std::transform function from the <algorithm> library along with the std::tolower function from the <cctype> library.


Here's an example code snippet that demonstrates how to convert a string to lowercase:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
#include <iostream>
#include <algorithm>
#include <cctype>
#include <string>

int main() {
  std::string str = "Hello, World!";
  
  std::transform(str.begin(), str.end(), str.begin(),
                 [](unsigned char c) { return std::tolower(c); });
  
  std::cout << str << std::endl;
  
  return 0;
}


In this example, the std::transform function applies the std::tolower function to each character in the string, converting it to lowercase. The lambda function [](unsigned char c) { return std::tolower(c); } is used as the transformation function.


After the transformation, the lowercase string is printed to the console using std::cout.