I'm following a tutorial for C++ and looking at strings and overloading with operators such as +=
, ==
, !=
etc. Currently I have a simple if-statement:
if(s1 < s2)
cout << s2 <<endl;
else
if(s2 < s1)
cout << s1 << endl;
else
cout << "Equal\n";
But how does this work, and how does the program decide which string is greater than another? looking around I've found a basic template declaration:
template<class charT, class traits, class Allocator>
bool operator< ( const basic_string<charT,traits,Allocator>& lhs,
const basic_string<charT,traits,Allocator>& rhs );
Does this define how <
works? If so, what does <charT,traits,Allocator>
mean / do?
Also do the following operators have any meaning for strings? -=
and *=
Java String compareTo() Method The method returns 0 if the string is equal to the other string. A value less than 0 is returned if the string is less than the other string (less characters) and a value greater than 0 if the string is greater than the other string (more characters).
The comparison operators also work on strings. To see if two strings are equal you simply write a boolean expression using the equality operator.
Using the == operator compares the object reference. Using the equals() method compares the value of the String . The same rule will be applied to all objects. When using the new operator, a new String will be created in the String pool even if there is a String with the same value.
The less-than operator on strings does a lexicographical comparison on the strings. This compares strings in the same way that they would be listed in dictionary order, generalized to work for strings with non-letter characters.
For example:
"a" < "b"
"a" < "ab"
"A" < "a" (Since A has ASCII value 65; a has a higher ASCII value)
"cat" < "caterpillar"
For more information, look at the std::lexicographical_compare
algorithm, which the less-than operator usually invokes.
As for -=
and *=
, neither of these operators are defined on strings. The only "arithmetic" operators defined are +
and +=
, which perform string concatenation.
Hope this helps!
The comparison operators implement lexicographic ordering of strings.
-=
and *=
are not defined for strings.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With