I will explain to you the example mentioned in the website I just gave you from it you will know your answer.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
|
// comparing apples with apples
#include <iostream>
#include <string>
using namespace std;
int main ()
{
string str1 ("green apple");
string str2 ("red apple");
if (str1.compare(str2) != 0)
cout << str1 << " is not " << str2 << "\n";
if (str1.compare(6,5,"apple") == 0)
cout << "still, " << str1 << " is an apple\n";
if (str2.compare(str2.size()-5,5,"apple") == 0)
cout << "and " << str2 << " is also an apple\n";
if (str1.compare(6,5,str2,4,5) == 0)
cout << "therefore, both are apples\n";
return 0;
}
|
OUTPUT
green apple is not red apple
still, green apple is an apple
and red apple is also an apple
therefore, both are apples |
First you get your two strings, which you are going to compare to each other.
1 2
|
string str1 ("green apple");
string str2 ("red apple");
|
In the following statement
1 2
|
if (str1.compare(str2) != 0)
cout << str1 << " is not " << str2 << "\n";
|
They compared str1 & str2. If the value returned from str1 compared to str2 is not 0
THEN print on the screen "
green apple is not red apple"
In the following statement
1 2
|
if (str1.compare(6,5,"apple") == 0)
cout << "still, " << str1 << " is an apple\n";
|
They compared str1 starting from after the sixth digit with the word "
apple". Since what after the sixth digit in "
green apple" was "
apple" meaning that it was similar to the word they compared it to. Which returned the value of 0. Therefore the if statement was true, which meant that it will print on the screen "
still, green apple is an apple.
In the following statement
1 2
|
if (str2.compare(str2.size()-5,5,"apple") == 0)
cout << "and " << str2 << " is also an apple\n";
|
Well this one I didn't understand it so nevermind this one.
In the following statement
1 2
|
if (str1.compare(6,5,str2,4,5) == 0)
cout << "therefore, both are apples\n";
|
In this one, they compared what came after str1's 6th digit with what came after str2's 4 digit. Since those were similar, the comparison would return the value of 0 meaning that it will print on the screen. The "5" mentioned in the statement "if (str1.compare(6,
5,str2,4,
5) == 0)" meant that it will compare only 5 digits.
Hope You understand this!!