C++

How to compare string in C++

Comparing strings is a very common task for any programming language. It is mainly used for validating the data, such as checking the username and password of the login information. The string comparison can be done by using a comparison operator or using built-in functions. Two string comparison functions used in C++ are, strcmp() and compare(). The strcmp() is a library function of C to compare two strings. The compare () is a built-in function of C++ to compare two strings. The ways to compare strings using comparison operators and functions have been explained in this tutorial.

Pre-requisite:

Before checking the examples of this tutorial, you have to check the g++ compiler is installed or not in the system. If you are using Visual Studio Code, then install the necessary extensions to compile the C++ source code to create the executable code. Here, the Visual Studio Code application has been used to compile and execute the C++ code.

Using Comparison Operator to compare string:

The most common way to compare strings in C++ is using the comparison operator. These are equal (==) and not equal (!=) operators. Create a C++ file with the following code to compare two string values using the comparison operator. According to the code, an URL address will be taken from the user and compared with other strings using an equal (==) operator. If the input value matches with any string of the ‘if’ condition, then the specific message will be printed; otherwise, the message of the ‘else’ part will be displayed.

#include<iostream>
using namespace std;

int main() {
  // Declare a string variable
  string url_addr;

  // Take a url address from the user
  cout<<"Enter the URL Address: ";
  cin>>url_addr;

  // Compare the input value with another string using equivalent operator
  if(url_addr == "google.com")
     cout<<"It is a search engine wensite."<<endl;
  else if(url_addr == "jooble.org")
     cout<<"It is a job searching website."<<endl;
  else if(url_addr == "linuxhint.com")
     cout<<"It is a blog website."<<endl;
  else
     cout<<"No information is added for this site."<<endl;

  return 0;
}

Output:

After executing the code, if the user typed ‘linuxhint.com‘ as input, the third ‘if’ condition will be returned True, and the following output will appear.

Using compare () function to compare string:

The compare () function compares two strings and returns 0 or 1 or -1 based on the matching result of the comparison. The meaning of the return values is given below.

  • The function will return 0 when both comparing strings are equal.
  • The function will return 1 when the first string is greater than the second string.
  • The function will return -1 when the first string is less than the second string.

Syntax:

int string1.compare(string2)

Create a C++ file with the following code to compare two string values with two input values using compare () function. The authentication of any user can be checked by comparing the values submitted by the users with the values of the authenticated user. This authentication process has been implemented in the following code. The valid email address and password have been stored into two string variables here. Next, these values have compared with the email address and the password taken from the user using compare () function. The logical AND operator has been used in the code to authenticate the user. The success message will be printed if both compare () functions return True. Otherwise, the failure message will be printed.

#include<iostream>
using namespace std;

int main() {

   //Initialialize two string variables
   string email("[email protected]");
   string password("linuxhint");

   //Declare two string variables
   string user_email;
   string user_password;

   //Take the email address from the user
   cout<<"Enter your email address:";
   cin>>user_email;

   //Take the password from the user
   cout<<"Enter your password:";
   cin>>user_password;

   //Check the username ans the password are valid or invalid
   if (user_email.compare(email) == 0 &&user_password.compare(password) == 0 )
       cout<<"Authentication Successful."<<endl;
   else
       cout<<"Email or password is invalid."<<endl;

  return 0;
}

Output:

After executing the code, if the user typed ‘[email protected]‘ as email address and ‘12345‘ as password, the third ‘if’ condition will be returned False, and the following output will appear.

After executing the code again, if the user typed ‘[email protected]‘ as email address and ‘linuxhint‘ as password, the third ‘if’ condition will be returned True, and the following output will appear.

Using strcmp() function to compare string:

The strcmp() is another function to compare strings in C++. It returns true if both the comparing strings are equal. The input parameters taken by this function are different from the compare() function. The compare function takes a string value as a parameter, and the strcmp() function takes the char array as a parameter. The syntax of this function is given below.

Syntax:

int strcmp ( const char * str1, const char * str2 );

Create a C++ file with the following code to compare two strings using the strcmp() function. Two character arrays of 100 elements have been declared in the code to store the string values taken by the users. The getline() function is used to store the user’s input into the char array variables. Next, the strcmp() function has used to check the input values are equal or not. If the function returns True, then the success message will be printed; otherwise, the failure message will be printed,

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

int main() {

  //Delare two string variables
  char chrData1[100], chrData2[100];

  //Take the first string data
  cout<<"Enter the first string:";
  cin.getline(chrData1, 100);

  //Take the second string data
  cout<<"Enter the second string:";
  cin.getline(chrData2, 100);

  if (strcmp(chrData1, chrData2)==0)
    printf("The strings are equal\n");
  else
    printf("The strings are not equal\n");

  return 0;
}

Output:

After executing the code, the string value, ‘hello‘ is given for both input values, and the following output will appear.

Conclusion:

Three ways to compare strings in C++ have been shown in this tutorial by using three simple examples. Both the uses of the comparison operator and the built-in functions for checking the equality of the strings have been described in this tutorial to help the new C++ programmers.

About the author

Fahmida Yesmin

I am a trainer of web programming courses. I like to write article or tutorial on various IT topics. I have a YouTube channel where many types of tutorials based on Ubuntu, Windows, Word, Excel, WordPress, Magento, Laravel etc. are published: Tutorials4u Help.