Is string::compare reliable to determine alphabetical order?

前端 未结 5 1605
太阳男子
太阳男子 2021-02-14 06:59

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 alphabetica

相关标签:
5条回答
  • 2021-02-14 07:28

    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);
    
    0 讨论(0)
  • 2021-02-14 07:30

    The specifications for the C and C++ language guarantee for lexical ordering, 'A' < 'B' < 'C' ... < 'Z'. The same is true for lowercase.

    The ordering for text digits is also guaranteed: '0' < ... < '9'.

    When working with multiple languages, many people create an array of characters. The array is searched for the character. Instead of comparing characters, the indices are compared.

    0 讨论(0)
  • 2021-02-14 07:47

    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.

    0 讨论(0)
  • 2021-02-14 07:52

    yes,

    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.

    For string objects, the result of a character comparison depends only on its character code (i.e., its ASCII code), so the result has some limited alphabetical or numerical ordering meaning.

    0 讨论(0)
  • 2021-02-14 07:52

    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.

    0 讨论(0)
提交回复
热议问题