String Compare Function - C++ Programming Tutorial
C++ Course / Strings / String Compare Function

String Compare Function

BLUF: Mastering String Compare Function is a critical step in becoming a proficient C++ developer. This lesson provides a deep dive into the syntax, performance considerations, and real-world applications of this concept.
Key Performance Insight: String Compare Function

C++ is renowned for its efficiency. Learn how String Compare Function enables low-level control and high-performance computing in the tutorial below.

C++ String compare

This function evaluates the string object's value against the specified sequence of characters provided as its parameter.

Syntax :

If we have two strings, str1 and str2, and we wish to compare them, the syntax for doing so would be:

Example

int k= str1.compare(str2);
  • 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

Example

#include<iostream>
using namespace std;
void main()
{
   string str1="Hello";
   string str2="javacpptutorial";
    int k= str1.compare(str2);
    if(k==0)
         cout<<"Both the strings are equal";
     else
       cout<<"Both the strings are unequal";

}

Output:

Output

Both the strings are unequal

When comparing the strings str1 and str2, with 'Hello' and 'javacpptutorial' as their respective values, the comparison method yields a negative integer value. Consequently, the 'if' condition does not validate, leading to the execution of the else statement which outputs "Both the strings are unequal".

Example 2

Example

#include<iostream>
using namespace std;
void main()
{
   string str1="Welcome to javacpptutorial";
   string str2="Welcome to javacpptutorial";
   int i=str1.compare(str2);
   if(i==0)
  cout<<"strings are equal";
else
cout<<"strings are not equal";
}

Output:

Output

Strings are equal

Input Required

This code uses input(). Please provide values below:

Logic Practice
Install Logic Practice
Add to home screen for a faster app-like experience