Home » C++ String compare() function

C++ String compare() function

by Online Tutorials Library

C++ String compare()

This function compares the value of the string object to the sequence of characters specified by its parameter.

Syntax :

Suppose str1 and str2 are two strings and we want to compare these two strings then its syntax would look like:

  • k==0 : If k contains value zero, it means both the strings are equal.
  • k!=0 : If k does contain value zero, it means both the strings are unequal.
  • k>0 : If k contains value more than zero, either the value of the first character is greater in the compared string or all the compared characters match but the compared string is longer.
  • k<0 : If k contains value less than zero, either the value of the first character is lower in the compared string or all the compared characters match but the compared string is shorter.

Example 1

Output:

Both the strings are unequal  

Consider two strings str1 and str2. str1 contains value ‘Hello’ and str2 contains value ‘tutoraspire’ ,We compare these two strings using compare method and this compare method always returns integer value.When we compare these two strings we get the value less than zero.Now,in this case ‘if’ condition fails then else statement will run and will print “Both the strings are unequal”.

Example 2

Output:

Strings are equal  

Next TopicC++ Strings

You may also like