Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is string::compare reliable to determine alphabetical order?

Tags:

c++

string

Simply put, if the input is always in the same case (here, lower case), and if the characters are always ASCII, can one use string::compare to determine reliably the alphabetical order of two strings?

Thus, with stringA.compare(stringB) if the result is 0, they are the same, if it is negative, stringA comes before stringB alphabetically , and if it is positive, stringA comes after?

like image 213
MPelletier Avatar asked Dec 06 '09 06:12

MPelletier


3 Answers

According to the docs at cplusplus.com,

The member function returns 0 if all the characters in the compared contents compare equal, a negative value if the first character that does not match compares to less in the object than in the comparing string, and a positive value in the opposite case.

So it will sort strings in ASCII order, which will be alphabetical for English strings (with no diacritical marks or other extended characters) of the same case.

like image 57
Moishe Lettvin Avatar answered Nov 06 '22 14:11

Moishe Lettvin


Yes, as long as all of the characters in both strings are of the same case, and as long as both strings consist only of letters, this will work.

compare is a member function, though, so you would call it like so:

stringA.compare(stringB);
like image 42
James McNellis Avatar answered Nov 06 '22 12:11

James McNellis


In C++, string is the instantiation of the template class basic_string with the default parameters: basic_string<char, char_traits<char>, allocator<char> >. The compare function in the basic_string template will use the char_traits<TChar>::compare function to determine the result value.

For std::string the ordering will be that of the default character code for the implementation (compiler) and that is usually ASCII order. If you require a different ordering (say you want to consider { a, á, à, â } as equivalent), you can instantiate a basic_string with your own char_traits<> implementation. providing a different compare function pointer.

like image 43
David Rodríguez - dribeas Avatar answered Nov 06 '22 13:11

David Rodríguez - dribeas