How To Convert String To Lowercase In C++

In C++, a string is a sequence of characters stored in memory that represents textual data. It is a data type that is a component of the STL and offers a practical way to work with text data.

A string is an object that has a variety of member functions for common operations like concatenation, substring extraction, and searching and may be dynamically scaled and altered. It can be initialized with a literal value or read in from user input.

All of the capital letters in a string are swapped out for their equivalent lowercase characters to convert it to lowercase. Any lowercase letters already present in the string are unaffected by this procedure.

Why to convert string to lowercase in C++

There are several reasons for converting a string to lowercase in C++:

  1. Consistency: Converting all input to lowercase allows for consistent data processing and comparisons.
  2. User input: Users may not always enter input in the expected format, so converting to lowercase can help ensure accurate data processing.
  3. String manipulation: Converting all strings to lowercase or uppercase might make the process simpler while searching, sorting, or filtering a huge group of strings.
  4. String comparisons can be aided by changing the case of the two strings because case matters when comparing two strings.
  5. Output formatting: Lowercase formatting is often preferred for certain types of output, such as web addresses or file names.

Method to convert string to lowercase in C++

There are several methods for converting a string to lowercase in C++:

  1. Using a loop and the tolower() function
  2. Using the transform() function with a lambda
  3. Using the boost library
  4. Using the range-based for loop and std::transform() function

Approach 1: Using a loop and the tolower() function

In this approach, we iterate through the characters of the string using a loop and call the tolower() function on each character to convert it to lowercase.

Sample Code:

#include <iostream>
#include <string>

int main() {
   std::string str = "HELLO WORLD";
  
   for (auto& c : str) {   // iterate through each character in the string
       c = tolower(c);     // convert the character to lowercase using tolower() function
   }
  
   std::cout << str << std::endl; // Output the modified string
   return 0;
}

Output:

hello world

Explanation:

  • We start by initializing a string ‘str’ with the value “HELLO WORLD”.
  • We then iterate through each character in the string using a range-based for loop.
  • Inside the loop, we call the tolower() function on each character and assign the result back to the original character. This converts each uppercase character to its lowercase equivalent.
  • Finally, we output the modified string to the console using the std::cout statement.
  • The output is the modified string “hello world” in all lowercase characters.

Approach 2: Using the transform() function with a lambda

In this approach, we use the “std::transform()” function along with a lambda function that calls “std::tolower()” on each character of the string to convert it to lowercase.

Sample Code :

#include <iostream>
#include <string>
#include <algorithm>

int main() {
   std::string str;
   std::cout << "Enter a string: ";
   std::getline(std::cin, str);  // get user input

   // Transform all characters in the string to lowercase using a lambda function
   std::transform(str.begin(), str.end(), str.begin(),
       [](unsigned char c){ return std::tolower(c); });

   std::cout << str << std::endl; // Output the modified string
   return 0;
}

Output:

Enter a string: Hello World
hello world

Explanation:

  • We start by declaring a string variable ‘str’ and use the ‘std::getline()’ function to get user input.
  • We then use the ‘std::transform()’ function to iterate through each character of the string and apply a lambda function to convert each character to lowercase.
  • The lambda function takes an ‘unsigned char’ parameter and returns its lowercase equivalent using the ‘std::tolower()’ function.
  • Finally, we output the modified string to the console using the ‘std::cout’ statement.
  • The output is the modified string in all lowercase characters.

 

Approach 3: Using the boost library

In this approach, we use the ‘boost::algorithm::to_lower()’ function from the Boost C++ library to convert the input string to lowercase.

Sample Code:

#include <iostream>
#include <string>
#include <boost/algorithm/string.hpp>

int main()
{
   std::string str;
   std::cout << "Enter a string: ";
   std::getline(std::cin, str); // get user input
   // Convert the string to lowercase using the to_lower() function from the Boost library
   boost::algorithm::to_lower(str);

   // Output the modified string
   std::cout << str << std::endl;

   return 0;
}

Output:

Enter a string: Hello World
hello world

Explanation:

  • We start by declaring a string variable ‘str’ and use the ‘std::getline()’ function to get user input.
  • We then use the ‘boost::algorithm::to_lower()’ function to convert the string to lowercase. This function takes a string reference as input and modifies the string in place.
  • Finally, we output the modified string to the console using the ‘std::cout’ statement.
  • The output is the modified string in all lowercase characters.

Note: This approach requires the Boost C++ library to be installed and linked in the project.

Approach 4: Using the range-based for loop and std::transform() function

In this approach, we use a combination of a range-based for loop and the ‘std::transform()’ function to convert the input string to lowercase.

Sample Code:

#include <iostream>
#include <string>
#include <algorithm>
#include <ranges>

int main() {
   std::string input; // Declare a string variable to store the user input
  
   std::cout << "Enter some text: "; // Prompt the user to enter some text
   std::getline(std::cin, input); // Read a line of text from the user and store it in the input variable
  
   // Use std::ranges::transform to convert the input string to lowercase
   std::ranges::transform(input, input.begin(), ::tolower);
  
   std::cout << "Here's your text in lowercase: " << input << std::endl; // Print the result to the console
  
   return 0; // Exit the program with a status code of 0 (success)
}

Output:

Enter a string: Hello World
hello world

Explanation:

  1. A std::string variable named input is declared to store the user input.
  2. The std::cout stream is used to print a message prompting the user to enter some text.
  3. The std::getline function is used to read a line of text from the user and store it in the input variable.
  4. The std::ranges::transform algorithm is used to convert the entire input string to lowercase.
  5. The ::tolower function is used as the transformation function to convert each character to lowercase.
  6. The result of the std::ranges::transform algorithm is stored back in the original input string using the input.begin() iterator.
  7. The result of the lowercase conversion is printed to the console using std::cout.

Best Approach:

There are several reasons why tolower() is a common method for converting strings to lowercase in C++:

  1. Built-in function: The C++ standard library includes the built-in function tolower(), making it immediately usable and requiring no additional setup or configuration.
  2. Easy to use: tolower() is a simple and straightforward function to use, requiring only a single character as input and returning the corresponding lowercase value.
  3. Widely supported: tolower() is a widely supported function across different compilers and operating systems, making it a reliable choice for cross-platform development.
  4. Efficient: tolower() is often implemented as a simple lookup table or bitwise operation, making it an efficient way to convert characters to lowercase.
  5. Standardized behavior: tolower() is defined by the C++ standard, ensuring consistent behavior across different implementations and avoiding potential compatibility issues.

Sample Problem:

Sample Problem 1:

A restaurant wants to create a system to manage their orders. However, the waiters and cooks are used to typing in the dishes in all caps, while the database can only recognize lowercase letters. The restaurant needs a program to convert the input to lowercase before storing it in the database.

Code

#include <iostream>
#include <string>
#include <algorithm>

int main() {
   // Define the string variable dish with the value "SPAGHETTI BOLOGNESE"
   std::string dish = "SPAGHETTI BOLOGNESE";
  
   // Use std::transform() and ::tolower() to convert the string to lowercase
   std::transform(dish.begin(), dish.end(), dish.begin(), ::tolower);
  
   // Output the lowercase string
   std::cout << "Dish: " << dish << std::endl;
  
   return 0;
}

Output:

Dish: spaghetti bolognese

Explanation:

  1. We start by declaring a string variable dish and initializing it to “SPAGHETTI BOLOGNESE”.
  2. The string is subsequently changed to lowercase by using the std::transform method.
  3. The beginning, end, and beginning of the output range are the three inputs that the std::transform method needs.
  4. Since we wish to change the original string, we utilise the input ranges dish.begin() and dish.end() and the output range dish.begin(). The final argument ::tolower is a function that converts each character in the input range to its lowercase equivalent.
  5. Finally, we use std::cout to output the resulting lowercase string.

In this scenario, we used the std::transform function with ::tolower to convert the string to lowercase. This is a useful method for converting strings to lowercase since it allows us to modify the original string directly and is also more concise than other methods like iterating through each character and converting them individually.

Sample problem 2:

A company stores the names of its employees in a text file. The company has recently decided to switch to a new employee database system, which requires all employee names to be in lowercase. Create a C++ programme that reads the text file containing the employee names, lowercases them, and then writes the lowercased names to a new text file.

Code:

#include <iostream>
#include <fstream>
#include <string>
#include <algorithm>

int main() {
   // Open the input and output files
   std::ifstream infile("employees.txt");
   std::ofstream outfile("employees_lower.txt");
  
   std::string line;
  
   // Read each line of the input file
   while (std::getline(infile, line)) {
       // Convert each character in the line to lowercase
       std::transform(line.begin(), line.end(), line.begin(), ::tolower);
      
       // Write the lowercase line to the output file
       outfile << line << std::endl;
   }
  
   // Close the input and output files
   infile.close();
   outfile.close();
  
   std::cout << "Conversion complete." << std::endl;
  
   return 0;
}

Output:

JOHN DOE
JANE SMITH
BOB JOHNSON
-
john doe
jane smith
bob johnson

Explanation:

  • The program reads the content of the “employees.txt” file, line by line.
  • The std::ifstream class is used to read from the file, and the input file stream is named “infile”.
  • The std::ofstream class is used to write to a file, and the output file stream is named “outfile”.
  • The program creates a string object named “line” to hold each line of text read from the input file.
  • In the while loop, the program reads each line from the input file and stores it in the “line” variable.
  • The std::transform function is used to convert each character in the line to lowercase, and the result is stored back in the “line” variable.
  • The transformed line is then written to the output file using the output file stream.
  • After all the lines have been read and converted to lowercase, both the input and output files are closed using the close() function.
  • Finally, a message is printed to the console indicating that the conversion is complete.

Sample Problem 3:

Suppose you are working on a text analysis project where you need to compare two strings for similarity. One of the common techniques for string comparison is to convert both strings to lowercase and then compare them. In this scenario, you can use the Boost library to convert a string to lowercase.

Code:

#include <iostream>
#include <string>
#include <boost/algorithm/string.hpp>

int main() {
   std::string str1 = "This is a Test String";
   std::string str2 = "this is a test string";
  
   // Convert str1 to lowercase
   boost::algorithm::to_lower(str1);
  
   // Compare the two strings
   if (str1 == str2) {
       std::cout << "The two strings are similar" << std::endl;
   } else {
       std::cout << "The two strings are not similar" << std::endl;
   }
  
   return 0;
}

Output:

The two strings are similar

Explanation:

  1. The code includes the necessary header files to use string and boost algorithm library functions.
  2. Two strings, str1 and str2 are declared and initialized with some values.
  3. The boost::algorithm::to_lower() function is called on str1 to convert it to lowercase.
  4. The if-else block checks if str1 is equal to str2 after the conversion to lowercase.
  5. If str1 and str2 are equal, then the program prints “The two strings are similar”. Otherwise, it prints “The two strings are not similar”.
  6. The program then returns 0 to indicate successful execution.

Sample Problem 4:

Suppose you have a database of customer names in uppercase letters, and you need to generate a report that displays all the names in lowercase letters for readability purposes. To accomplish this task, you can use the range-based for loop and the std::transform() function to convert each name in the database to lowercase.

Code:

#include <iostream>
#include <string>
#include <algorithm>

int main() {
   // Create a vector of customer names in uppercase letters
   std::vector<std::string> customers = {"JOHN DOE", "JANE DOE", "BOB SMITH", "SUE SMITH"};

   // Convert each name to lowercase using the range-based for loop and std::transform() function
   for (auto& customer : customers) {
       std::transform(customer.begin(), customer.end(), customer.begin(), ::tolower);
   }

   // Print the customer names in lowercase
   std::cout << "Customer names in lowercase:" << std::endl;
   for (const auto& customer : customers) {
       std::cout << customer << std::endl;
   }

   return 0;
}

Output:

Customer names in lowercase:
john doe
jane doe
bob smith
sue smith

Explanation:

  1. The code defines a vector named customers that contains four strings representing the names of customers in uppercase letters.
  2. The range-based for loop is used to iterate through each element of the customer’s vector.
  3. The std::transform() method is used to lowercase the string for each element.
  4. The string’s characters need all be changed to lowercase, therefore the fourth argument to std::transform() specifies the::tolower method.
  5. After converting all the customer names to lowercase, the code uses another range-based for loop to print each name to the console.
  6. The const keyword is used to indicate that the customer variable should not be modified during the iteration.
  7. Finally, the code returns 0 to indicate successful execution.

Conclusion:

In conclusion, there are several approaches to convert a string to lowercase in C++. The most commonly used methods include using a loop and the ‘tolower()’ function. Depending on the precise requirements of the project, each strategy offers pros and cons.

However, in most cases, the ‘transform()’ function with a lambda expression is considered the most efficient and easiest-to-read approach.

The choice of approach ultimately depends on the specific needs of the project, such as efficiency, readability, and library dependencies.