Comparing Strings in C++

  1. Home
  2. Tutorials
  3. CPP
  4. CPP Programs
  5. String Handling
  6. Program

Source Code:

#include <iostream>
#include <cstring>

//standard namespace
using namespace std;

Source code for string
comparison in C++

int main () {
  char str1[30] = "Institute A";
  char str2[30] = "Institute";
  int x = strcmp(str1,str2);
  if(x == 0) {
      cout<<"Both strings are equal";
  } else if(x == 1) {
      cout<<"First string is greater";
  } else {
      cout<<"Second string is greater";

  return 0;


How to compare string in C++ using Dev-C++


In this program example two strings are initialized using character arrays. For this purpose we use here char data type. Then these strings are compare using strcmp() function. strcmp function return an integer value depending upon comparison. The possible values from strcmp function are as follows.

Sr. Return Value Meaning
1 0 Zero means both input strings are equal.
2 1 When strcmp function return one it means first provided string is greater.
3 -1 -1 return value means second parameter/string is greater.

After comparison we store the resultant value in an integer type variable called x. Later this x identifier is checked using if else statement to display proper/descriptive message on the screen.

Login to TRACK of Comments.