C++ tutorial-compare function


C++ String Manipulation

C++ compare() function

The compare() function is used to two strings. The compare() function has two forms. The first form compares all characters in a string with another string. The second form compares part of string with another string. This proportion of string is taken out by starting from the start argument and the num_chars argument specifies the number of characters to be taken out. This function returns less than zero if the invoking string is less than the string specified as an argument. It returns zero if both strings are equal.

compare(string);

compare(start, num_chars, string);



Example:

#include <cstdlib>
#include <iostream>
#include <conio.h>


using namespace std;


void strmanip(){

  string st1,st2;
  cout<<"Enter your first string:";
  cin>>st1;
  cout<<"Enter your second string:";
  cin>>st2;
  if(st1.compare(st2)>0) cout<<"First string is greater than second string."<<endl;
  else if(st1.compare(0, st2.size(),st2)<0) cout<<"First string is less than second string."<<endl;
  else cout<<"Both strings are equal."<<endl;

}

int main(){

  strmanip();
  getch();
  return 0;

}


Comments




This website intents to provide free and high quality tutorials, examples, exercises and solutions, questions and answers of programming and scripting languages:
C, C++, C#, Java, VB.NET, Python, VBA,PHP & Mysql, SQL, JSP, ASP.NET,HTML, CSS, JQuery, JavaScript and other applications such as MS Excel, MS Access, and MS Word. However, we don't guarantee all things of the web are accurate. If you find any error, please report it then we will take actions to correct it as soon as possible.