Back to Homepage
Friday 16 August 2024
33

C++ How to compare strings

In C++, comparing strings is a common task that can be accomplished using several methods depending on the context and string type. You might need to compare strings for equality, lexicographical order, or to determine which string is greater or lesser.

Using strcmp Function

The strcmp function, found in the <cstring> library, compares two C-style strings (null-terminated character arrays). It returns:

  • 0 if the strings are equal.
  • A negative value if the first string is less than the second.
  • A positive value if the first string is greater than the second.

Example:

#include <cstring>
#include <iostream>

int main() {
    const char* str1 = "Hello";
    const char* str2 = "World";
    if (strcmp(str1, str2) == 0) {
        std::cout << "Strings are equal";
    } else {
        std::cout << "Strings are not equal";
    }
    return 0;
}

Using std::string's compare() Method

When dealing with std::string objects, the compare() method is a versatile way to compare strings. It works similarly to strcmp, returning 0 for equal strings, a negative value if the first string is lexicographically smaller, and a positive value if it is larger.

Example:

#include <iostream>
#include <string>

int main() {
    std::string str1 = "Hello";
    std::string str2 = "World";
    if (str1.compare(str2) == 0) {
        std::cout << "Strings are equal";
    } else {
        std::cout << "Strings are not equal";
    }
    return 0;
}

Using the Equality Operator (==)

The equality operator (==) is the simplest way to compare std::string objects in C++. It checks for equality and returns a boolean value.

Example:

#include <iostream>
#include <string>

int main() {
    std::string str1 = "Hello";
    std::string str2 = "Hello";
    if (str1 == str2) {
        std::cout << "Strings are equal";
    } else {
        std::cout << "Strings are not equal";
    }
    return 0;
}

Examples of String Comparison in C++

1. Case-sensitive comparison:

std::string str1 = "hello";
    std::string str2 = "Hello";
    bool areEqual = (str1 == str2); // false

2. Case-insensitive comparison (using std::transform):

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

    int main() {
        std::string str1 = "Hello";
        std::string str2 = "hello";

        std::transform(str1.begin(), str1.end(), str1.begin(), ::tolower);
        std::transform(str2.begin(), str2.end(), str2.begin(), ::tolower);

        if (str1 == str2) {
            std::cout << "Strings are equal (case-insensitive)";
        } else {
            std::cout << "Strings are not equal";
        }
        return 0;
    }

References

For more detailed information, you can refer to the official C++ documentation:

Share:
Created by:
Author photo

Jorge García

Fullstack developer