0

Advance Examples on tolower string C++

Tolower String C++

Example 1: Case-Insensitive String Comparison

#include <iostream>
#include <cstring>
int main() {
    std::string str1 = “Hello”;
    std::string str2 = “HELLO”;
    if (strcasecmp(str1.c_str(), str2.c_str()) == 0) {
        std::cout << “Case-insensitive comparison: Strings are equal.” << std::endl;
    } else {
        std::cout << “Case-insensitive comparison: Strings are not equal.” << std::endl;
    }
    return 0;
}

Explanation: This example uses the strcasecmp function to perform a case-insensitive string comparison. It converts both strings to lowercase and then compares them.

 

Example 2: Remove Duplicates from a Case-Insensitive String

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

int main() {
std::string input = “aABBbCCcd”;

std::sort(input.begin(), input.end());
auto last = std::unique(input.begin(), input.end());
input.erase(last, input.end());

std::transform(input.begin(), input.end(), input.begin(), ::tolower);

std::cout << “Case-insensitive unique characters: ” << input << std::endl;

return 0;
}

Explanation: This example combines std::sort and std::unique to remove duplicate characters from the string in a case-insensitive manner. The result is then transformed to lowercase using std::transform.

Leave a Reply

Your email address will not be published. Required fields are marked *