OneBite.Dev - Coding blog in a bite size

Compare Two Strings In C++

Code snippet for how to Compare Two Strings In C++ with sample and detail explanation

In C++, the comparison of two strings is a frequently encountered task, which can be approached in a variety of ways. This article will explain one of those methods, including a detailed examination of the code.

Code snippet for Comparing Two Strings

Here is a simple C++ code snippet that compares two strings:

#include <string>
#include <iostream>

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;
}

Code Explanation for Comparing Two Strings

Let’s break down the steps for the given code snippet:

First, we include two required libraries:

  • #include <string>: This is the C++ Standard Library for strings. We need to use it because we are using strings in our code.
  • #include <iostream>: This library allows input/output operations. We will perform output operations using the ‘cout’ object.

In the ‘main’ function where our code resides:

  • We first declare two strings str1 and str2, assigning them with values “Hello” and “World” respectively.
  • Then, we use the compare function to compare str1 and str2. This function compares the value of the string object (or a substring) to the sequence of characters specified. If both strings are equal, it returns 0.
  • We use an if-else statement to check the output of the compare function. If it returns 0, the strings are equal and it will print “Strings are equal,” otherwise, it prints “Strings are not equal.”

Please note, in the case of this code, “Hello” and “World” are not the same, so the output will be “Strings are not equal.”

Remember that this function is case sensitive. So, “hello” and “Hello” would be considered unequal.

That’s it, this is the simplest way in C++ to compare two strings. There are other methods also available in C++ to compare two strings, and this approach is one of the most straightforward.

c-plus-plus