DEV Community

Cover image for Compare two string in C++
Lalit Kumar
Lalit Kumar

Posted on

Compare two string in C++

In this post, we will see how to know if two strings are equal in ANSI C since we cannot simply use the operator ==to compare strings, they are a complex thing.

Table of contents:

  • strcmp function in C.
  • Compare strings in C using strcmp.
  • Know if two strings are equal using strcmp. Let's see how to use strcmp to compare strings in C and find out if both are the same since strings are actually a set of characters within ANSI C.

Strcmp function in C:

As in PHP, in C there is the function strcmpthat means "string compare". This function can return 0, a number greater than 0, or a number less than 0.

I know, it sounds confusing but let's see.

The function will strcmpreturn if the strings are equal. In case the first is "less" than the second, it will return a negative number, and finally if the first is greater than the second, it will return a positive number.

Usually, these numbers are 0, -1 and 1, but we can make the comparisons based on 0 (that is if it is less than zero, equal to zero or greater than zero). Read more

Top comments (1)

Collapse
 
bluma profile image
Roman Diviš

Title and tags are really misleading. Whole article is about C and not C++. That is confusing for beginners as in c++ exists string class and due to operator overloading there are comparison operators ==, >, <, ...