How To Convert Uppercase To Lowercase In C++

The “tolower()” function in C++ is used to convert uppercase characters to lowercase mostly, and works only for ASCII characters. It is commonly used by looping through each character in a string and using the function to change each character to lowercase. The modified characters can be stored in a new string or the original string can be modified.

The process for converting non-ASCII characters to lowercase may change, though. In short, “tolower()” is a useful function in C++ for converting ASCII uppercase characters to lowercase.

Why conversion uppercase to lowercase in C++ is important

Converting uppercase to lowercase in C++ can be important for several reasons:

  1. Consistency: If you are comparing strings or characters, it is important that the case is consistent.
  2. User Input: When dealing with user input, it is common to convert everything to lowercase to make it easier to handle.
  3. Output Formatting: You might want to convert everything to lowercase or uppercase in some circumstances in order to format the output.
  4. String Manipulation: Making all characters lowercase or uppercase can make it simpler to modify strings when working with them.
  5. Standardization: Converting everything to lowercase or uppercase can help ensure that the data is consistent and easy to work with.

Method to convert uppercase to lowercase in C++

There are several approaches for converting uppercase to lowercase in c++. Here are four commonly used methods:

  1. Using the “tolower()” Function
  2. Using the Bitwise Operator
  3. Using the Standard Library Function “transform()”
  4. Using the Boost Library

Approach 1: Using the “tolower()” Function

Using the “tolower()” function included into C++ is one of the easiest and most popular ways to change uppercase to lowercase. The lowercase equivalent of a single character entered into this method is returned.

Code:

#include <iostream> 
#include <cctype>   // include ctype library for tolower() function

int main()
{
   char uppercase = 'A';                                 // declare a char variable named uppercase and initialize it to the character 'A'
   char lowercase = std::tolower(uppercase);             // use the tolower() function from the ctype library to convert the uppercase character to lowercase and store it in a new char variable named lowercase
   std::cout << "Uppercase: " << uppercase << std::endl; // output the value of the uppercase variable to the console
   std::cout << "Lowercase: " << lowercase << std::endl; // output the value of the lowercase variable to the console
   return 0;                                             // return 0 to indicate successful program execution
}

Output:

Uppercase: A
Lowercase: a

Explanation:

  • The code first declares a character variable “uppercase” and initializes it with the value ‘A’.
  • The “tolower()” function is called with “uppercase” as its argument, and the result is stored in the “lowercase” variable.
  • The “std::cout” statements are used to print the values of both variables to the console.
  • When the program is run, the output shows that the uppercase character ‘A’ has been successfully converted to its lowercase equivalent ‘a’ using the “tolower()” function.

Approach 2: Using the Bitwise Operator

Using a bitwise operator in C++ is another method for changing a single uppercase character to a lowercase equivalent. Specifically, you can use the bitwise OR operator “|” with the value 0x20 to convert an uppercase ASCII character to its lowercase equivalent.

Code:

#include <iostream>

int main() {
   char uppercase = 'B'; // define an uppercase character to convert
   char lowercase = uppercase | 0x20; // convert the uppercase character to lowercase using a bitwise OR operation
   std::cout << "Uppercase: " << uppercase << std::endl; // output the original uppercase character
   std::cout << "Lowercase: " << lowercase << std::endl; // output the converted lowercase character
   return 0;
}

Output:

Uppercase: B
Lowercase: b

Explanation:

  • The code first declares a character variable “uppercase” and initializes it with the value ‘B’.
  • The bitwise OR operator “|” is used to set the 6th bit (counting from 0) of “uppercase” to 1, which corresponds to the ASCII value for the lowercase equivalent of ‘B’.
  • The resulting value is stored in the “lowercase” variable.
  • The “std::cout” statements are used to print the values of both variables to the console.
  • When the programme is run, the output demonstrates that the bitwise OR operator was successfully used to change the capital character “B” to its lowercase equivalent “b.”

Approach 3: Using the Standard Library Function “transform()”

A flexible function called “transform()” is offered by the C++ Standard Library and can be used to apply a specific function to each element in a range, including a string. By using a lambda function with “transform()”, you can apply the “tolower()” function to each character in a string to convert the entire string to lowercase.

Code:

#include <iostream>    
#include <algorithm>
#include <string>       // Includes the standard string library

int main() {
   std::string str = "CONVERT TO LOWERCASE";   // Declares and initializes a string variable named 'str'
  
   // Transforms each character of 'str' to its lowercase equivalent using the lambda function provided
   std::transform(str.begin(), str.end(), str.begin(),
                  [](unsigned char c){ return std::tolower(c); });
  
   // Outputs the original string and the transformed string to the console
   std::cout << "Original: " << "CONVERT TO LOWERCASE" << std::endl;
   std::cout << "Lowercase: " << str << std::endl;
  
   return 0;   // Indicates the end of the program
}

Output:

Original: CONVERT TO LOWERCASE
Lowercase: convert to lowercase

Explanation:

  • The code first declares a string variable “str” and initializes it with the value “CONVERT TO LOWERCASE”.
  • The “transform()” function is called with three arguments: the beginning and end iterators of the “str” string, and a lambda function that takes an unsigned char as input and returns its lowercase equivalent using the “tolower()” function.
  • The “transform()” function modifies the “str” string in place, applying the lambda function to each character in the string to convert it to lowercase.
  • The “std::cout” statements are used to print the original and converted strings to the console.
  • The “transform()” function, in addition to the lambda function that uses the “tolower()” function on each character, successfully transforms the entire string to lowercase when the program is run.

Approach 4: Using the Boost Library

Another approach to converting a string to lowercase in C++ is to use the Boost Library, which provides a range of utilities for working with strings and other data structures. The Boost Library includes a string algorithm called “to_lower()” that can be used to convert a string to lowercase.

Code:

#include <iostream>             
#include <string>                // Include string library
#include <boost/algorithm/string.hpp>  // Include boost library for to_lower function

int main() {
   std::string str = "CONVERT TO LOWERCASE";   // Declare string variable
   boost::algorithm::to_lower(str);            // Convert all characters in string to lowercase using boost library
   std::cout << "Original: " << "CONVERT TO LOWERCASE" << std::endl;    // Output original string
   std::cout << "Lowercase: " << str << std::endl;                     // Output lowercase string

   return 0;     
}

Output:

Original: CONVERT TO LOWERCASE
Lowercase: convert to lowercase

Explanation:

  • The code first declares a string variable “str” and initializes it with the value “CONVERT TO LOWERCASE”.
  • The “to_lower()” function from the Boost Library is called with “str” as its argument to convert the entire string to lowercase.
  • The “std::cout” statements are used to print the original and converted strings to the console.
  • When the program is run, the output shows that the entire string has been successfully converted to lowercase using the “to_lower()” function from the Boost Library.

Best Approach:

The “tolower()” method is a standard library function in C++ that is used to convert uppercase characters to their corresponding lowercase representation. For numerous reasons, this method has been considered the best strategy for transforming uppercase to lowercase in C++:

  1. Standardization: The “tolower()” method is a common and frequently used function that has undergone extensive testing and optimization because it is a component of the C++ standard library. As a result, developers can also choose it with confidence and safety.
  2. Efficiency: An effective implementation of the “tolower()” method reduces the time and memory needed to transform a string from uppercase to lowercase.
  3. Flexibility: The “tolower()” method is a generic function that can be used to convert any character to its lowercase representation, not just uppercase characters.
  4. Ease of use: The “tolower()” method is easy to use and requires minimal code to implement.

Sample Problem converting uppercase to lowercase in c++

Sample Problem 1(Using the “tolower()” Function):

A software company has a database of user information that includes their usernames. However, the usernames were stored in all uppercase letters and the company wants to convert them to lowercase letters for consistency and ease of use.

Code:

#include <iostream>
#include <string>
using namespace std;

int main() {
   // Define a string variable to hold the username
   string username;

   // Get user input for the username
   cout << "Enter your username: ";
   cin >> username;

   // Loop through each character in the username and convert to lowercase using tolower()
   for (char& c : username) {
       c = tolower(c);
   }

   // Print the lowercase username to the console
   cout << "Your lowercase username is: " << username << endl;

   return 0;
}

Output:

Enter your username: MyUserName
Your lowercase username is: myusername

Explanation:

  • The #include directive is used to include the necessary header files iostream and string.
  • The using namespace std statement is used to avoid having to prefix standard library functions and objects with std::.
  • The main() function is the entry point of the program.
  • A string variable username is defined to hold the user input.
  • The user is prompted to enter their username using cout and cin.
  • A loop is used to iterate through each character in the username.
  • The tolower() function is used to convert each character to its lowercase equivalent.
  • The char& type is used instead of char to ensure that the changes made to the characters in the string are reflected in the original string variable.
  • The lowercase username is printed to the console using cout.
  • The return 0; statement is used to indicate successful termination of the program.

Sample Problem 2 (Using the “tolower()” Function):

You have been tasked with developing a program that will read in a large text file and convert all the uppercase characters to lowercase. The program must be able to handle files of varying lengths and should output the converted text to a new file.

Code:

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main() {
   // Define variables to hold file paths and input/output streams
   string input_file_path, output_file_path;
   ifstream input_file_stream;
   ofstream output_file_stream;

   // Get user input for file paths
   cout << "Enter the input file path: ";
   getline(cin, input_file_path);
   cout << "Enter the output file path: ";
   getline(cin, output_file_path);

   // Open input file stream and check for errors
   input_file_stream.open(input_file_path);
   if (!input_file_stream) {
       cerr << "Error: Unable to open input file" << endl;
       return 1;
   }

   // Open output file stream and check for errors
   output_file_stream.open(output_file_path);
   if (!output_file_stream) {
       cerr << "Error: Unable to open output file" << endl;
       return 1;
   }

   // Define variable to hold each line of input
   string line;

   // Loop through each line of input and convert uppercase characters to lowercase
   while (getline(input_file_stream, line)) {
       for (char& c : line) {
           if (isupper(c)) {
               c = tolower(c);
           }
       }
       // Write the converted line to the output file
       output_file_stream << line << endl;
   }

   // Close the input and output file streams
   input_file_stream.close();
   output_file_stream.close();

   cout << "Conversion complete. Check the output file for the converted text." << endl;

   return 0;
}

Output:

Enter the input file path: input.txt
Enter the output file path: output.txt
Conversion complete. Check the output file for the converted text.

Explanation:

  • The program first declares variables for the input file path, output file path, input file stream, and output file stream.
  • It then prompts the user for the input and output file paths using getline() to get a string with spaces.
  • Next, the program opens the input file stream and checks for errors using the open() method and the ! operator to check if the stream failed to open.
  • The program does the same for the output file stream.
  • The program then declares a string variable to hold each line of input and uses a while loop with getline() to read in each line of the input file.
  • Within the while loop, the program uses a for loop to iterate through each character of the line and check if it is an uppercase letter using isupper().
  • If a character is uppercase, it converts it to lowercase using tolower().
  • The program then writes the converted line to the output file using the << operator and adds a newline character with endl.
  • Finally, the program closes the input and output file streams and prints a message to the console indicating that the conversion is complete.

Sample Problem 3 (Using the Bitwise Operator):

A company has a database of employee information, including their names and job titles, stored in all caps. The company is updating their HR system and wants to convert all the names and job titles to lowercase for consistency and readability.

Write a C++ program to read in the names and job titles of the employees, convert them to lowercase using bitwise operators, and display the updated information.

Code:

#include <iostream>
#include <string>

int main() {
   int numEmployees;
   std::cout << "Enter the number of employees: ";
   std::cin >> numEmployees;
   std::cin.ignore(); // ignore the newline character left in the input stream

   for (int i = 1; i <= numEmployees; i++) {
       std::string name, jobTitle;
       std::cout << "Enter employee #" << i << " name: ";
       std::getline(std::cin, name);
       std::cout << "Enter employee #" << i << " job title: ";
       std::getline(std::cin, jobTitle);

       // Convert name to lowercase
       for (char& c : name) {
           c |= 0x20; // flip the 6th bit to convert uppercase to lowercase
       }

       // Convert job title to lowercase
       for (char& c : jobTitle) {
           c |= 0x20; // flip the 6th bit to convert uppercase to lowercase
       }

       std::cout << "Employee #" << i << " name: " << name << std::endl;
       std::cout << "Employee #" << i << " job title: " << jobTitle << std::endl;
   }

   return 0;
}

Output:

Enter the number of employees: 3
Enter employee #1 name: JOHN DOE
Enter employee #1 job title: SENIOR DEVELOPER
Enter employee #2 name: JANE SMITH
Enter employee #2 job title: MANAGER
Enter employee #3 name: BILL JOHNSON
Enter employee #3 job title: JUNIOR DEVELOPER

Employee #1 name: john doe
Employee #1 job title: senior developer
Employee #2 name: jane smith
Employee #2 job title: manager
Employee #3 name: bill johnson
Employee #3 job title: junior developer

Explanation:

  1. The code prompts the user to enter the number of employees and reads in the value using std::cin.
  2. The user is prompted to provide the name and job title for each employee using std::input after a for loop iterates over each employee. to read in the values, use getline().
  3. Two for loops are used to convert the name and job title to lowercase. The bitwise OR operator (|) flips the sixth bit (0x20 in hexadecimal) of each uppercase character in the ASCII code to make it lowercase as each loop iterates over each character in the string.
  4. Finally, the employee’s name and job title in lowercase are printed out using std::cout.

Note that this method only works for ASCII characters, and there are more efficient ways to convert strings to lowercase using the standard library or other libraries.

Sample Problem 4 (Using “transform()” function):

Suppose you are building a text editor that has a feature to highlight all the occurrences of a particular word in a document. You must locate and highlight every instance of a word, whether it appears in the page in uppercase or lowercase, that a user types into the search box. To accomplish this and run a case-insensitive search, you must change all uppercase instances of the search word to lowercase.

Code:

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

int main() {
   std::string document = "This is a sample document to test the highlighting feature. The sample WORD should be highlighted.";
   std::string searchTerm = "word";

   // Convert the search term to lowercase
   std::transform(searchTerm.begin(), searchTerm.end(), searchTerm.begin(), ::tolower);

   // Find all occurrences of the search term
   std::string::size_type pos = document.find(searchTerm);
   while (pos != std::string::npos) {
       // Highlight the occurrence of the search term
       document.replace(pos, searchTerm.length(), "\033[1;31m" + searchTerm + "\033[0m");
      
       // Find the next occurrence of the search term
       pos = document.find(searchTerm, pos + 1);
   }

   // Print the highlighted document
   std::cout << document << std::endl;

   return 0;
}

Output:

This is a sample document to test the highlighting feature. The sample WORD should be highlighted.

After running the program with the search term “word”, the output is:

This is a sample document to test the highlighting feature. The sample \033[1;31mword\033[0m should be highlighted.

#In this example, the std::transform() function is used to convert the search term to lowercase before searching for its occurrences in the document. The document is then searched for all occurrences of the search term, and each occurrence is highlighted using ANSI escape codes.

Explanation:

  1. A sample document and search term are initialized as strings.
  2. The search term is converted to lowercase using the std::transform() function.
  3. The std::string::find() function is used to find the first occurrence of the search term in the document.
  4. A loop is initiated to continue finding and highlighting all occurrences of the search term in the document.
  5. For each occurrence, the std::string::replace() function is used to replace the search term with the same term surrounded by escape codes for red color highlighting.
  6. The position of the next occurrence of the search term is found by calling std::string::find() starting from the current position + 1.
  7. Once all occurrences of the search term have been found and highlighted, the modified document is printed to the console.

Sample problem 5 (Using the Boost Library):

The user is prompted to enter their name, which may be in uppercase or lowercase letters. To ensure consistency and ease of processing, it is desirable to convert the user’s input to lowercase letters.

Using the Boost Library, we can use the to_lower() function to achieve this. Here’s an example code snippet:

Code:

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

int main() {
   std::string playerName;
   std::cout << "Enter your name: ";
   std::getline(std::cin, playerName);

   boost::algorithm::to_lower(playerName);

   std::cout << "Hello, " << playerName << "!" << std::endl;

   return 0;
}

Output:

Enter your name: JOE
Hello, joe!

Explanation:

  • The program includes the necessary headers: iostream, string, and boost/algorithm/string.hpp.
  • The main() function is defined.
  • A string variable called playerName is declared to store the user’s name.
  • The user is prompted to enter their name using std::cout and std::getline is used to read the input.
  • The Boost library function to_lower is used to convert the string to lowercase.
  • The modified string is output to the console along with a greeting message.
  • The program returns 0 to indicate successful completion.

Conclusion

In summary, converting uppercase to lowercase in C++ is a crucial operation that can be achieved through several methods. The std::transform() function provides simplicity, versatility, and compatibility with other library functions

The std::tolower() function can also be used with a for loop or a range-based for loop. The best approach relies on the particular needs of the current task. Converting uppercase to lowercase ensures consistency and reduces errors in string handling, input processing, and output formatting.