3 Ways to Compare Strings in C++

In this tutorial, we’ll learn methods to compare strings in C++. Consider a scenario wherein you are required to enter your name and password to login to a particular website. In such cases, at the back end, we need to build and script functions to check and compare the input string (login details) with the string stored in the data base.

So, relating it here, in this article, will be understanding the Ways to compare string in C++ language.


Techniques to Compare Strings in C++

Strings in C++ can be compared using either of the following techniques:

  • String strcmp() function
  • In-built compare() function
  • C++ Relational Operators ( ‘==’ , ‘!=’ )

1. String strcmp() function in C++

C++ String has got in-built functions to manipulate and deal with data of string type. In order to compare two strings, we can use String’s strcmp() function.

The strcmp() function is a C library function used to compare two strings in a lexicographical manner.

Syntax:

  • The function returns 0 if both the strings are equal or the same.
  • The input string has to be a char array of C-style string.
  • The strcmp() compares the strings in a case-sensitive form as well.

Example 1:

Output:

Example 2:

Output:


2. The compare() function in C++

C++ has in-built compare() function in order to compare two strings efficiently.

The compare() function compares two strings and returns the following values according to the matching cases:

  • Returns 0, if both the strings are the same.
  • Returns <0, if the value of the character of the first string is smaller as compared to the second string input.
  • Results out to be >0, when the second string is greater in comparison.

Syntax:

Example 1:

In the above example, we have compared string 1 with string 2. As clearly seen, both the strings are the same lexicographically, it returns 0.

Output:

Example 2:

In the above snippet of code, we have compared a string with another input string to the compare() function directly.

Output:


3. Relational Operators in C++

C++ Relational operators such as ‘==’ and ‘!=’ can be useful in the comparison of string at an ease.

Syntax:

Example 1: Using C++ ‘==’ operator

Output:

Example 2: Using C++ ‘!=’ operator

Output:


Conclusion

In this article, we have understood various ways to compare strings in C++ Language.


References

By admin

Leave a Reply

%d bloggers like this: