+ 8
Why this code give an output -1, 0, and 1
string str1("green apple"); string str2("red apple"); 1. cout << str1.compare(4, 5,"apple") << endl; 2. cout << str1.compare(5, 5,"apple") << endl; 3. cout << str1.compare(6, 5,"apple") << endl; cout << endl; 4. cout << str1.compare(4, 5, str2, 4, 5) << endl; 5. cout << str1.compare(5, 5, str2, 4, 5) << endl; 6. cout << str1.compare(6, 5, str2, 4, 5) << endl; cout << endl; 7. cout << str2.compare(str2.size()-4, 5, "apple") << endl; 8. cout << str2.compare(str2.size()-5, 5, "apple") << endl; 9. cout << str2.compare(str2.size()-6, 5, "apple") << endl; Output: 1 -1 0 1 -1 0 1 0 -1 Please everyone, Give me some explanation about it...
5 Answers
+ 9
First take a look at the .compare syntax:
std::str.compare(pos, len, stringToMatch);
where
pos indicates the starting position(character/index) of the string you are matching.
Note that counting of index in strings also starts from 0.
So if you put 5 as pos, it means 6th index.
Second is the len, which specifies the length(substring) that you want match from the str.
So now in your first example
str1.compare(5, 5, "apple") ;
here pos = 5, which means 6th index,
length = 5
now str1 = green apple
We see ' '(space) at 6th index whose ASCII value is 32 and on the other side first character is 'a' whose ASCII value is 97.
That's why it returned -1.
Same logic applied to your other examples (4, 5, "apple") and (7, 5, "apple")
And for your last example (11, 5, "apple")
Here notice that pos is 11 which means 12th index
But 12th index doesn't exist in str1. So if the index if out of range, it throws an error and that's why it's giving -5 as out of range error.
+ 9
.compare function returns an integer value rather than the boolean.
If it returns 0, means that both strings are equal.
If it returns -1, means that first character of the string (one you are matching) is less than the first character of the other string (one you are matching with).
If it returns 1, means that first character of the string (one you are matching) is greater than the first character of the other string (one you are matching with).
Note that strings are compared character by character with their ASCII values
+ 8
Good, that was explain me a whole thing..
Thanks nAutAxH AhmAd
+ 7
Thanks, by reading your explanation. there is something i wanna to ask nAutAxH AhmAd. for example;
cout << str1.compare(5, 5, "apple") << endl;
how it can give an output -1?
When i set the parameter (4,5, "apple") or (7,5,"apple) it give 1 for the output. Another than that, when i set the parameter (11, 5, "apple) it give an output -5?
+ 2
you are comparing 2 string....
in older version it will give the character difference but now in new version it will give 0,1,-1 value
0 when str2==str1
1 when str2>str1
-1 when str2<str1