88 lines · plain
1.. title:: clang-tidy - readability-string-compare2 3readability-string-compare4==========================5 6Finds string comparisons using the compare method.7 8A common mistake is to use the string's ``compare`` method instead of using the9equality or inequality operators. The compare method is intended for sorting10functions and thus returns a negative number, a positive number or11zero depending on the lexicographical relationship between the strings12compared. If an equality or inequality check can suffice, that is recommended.13This is recommended to avoid the risk of incorrect interpretation of the return14value and to simplify the code. The string equality and inequality operators15can also be faster than the ``compare`` method due to early termination.16 17Example18-------19 20.. code-block:: c++21 22 // The same rules apply to std::string_view.23 std::string str1{"a"};24 std::string str2{"b"};25 26 // use str1 != str2 instead.27 if (str1.compare(str2)) {28 }29 30 // use str1 == str2 instead.31 if (!str1.compare(str2)) {32 }33 34 // use str1 == str2 instead.35 if (str1.compare(str2) == 0) {36 }37 38 // use str1 != str2 instead.39 if (str1.compare(str2) != 0) {40 }41 42 // use str1 == str2 instead.43 if (0 == str1.compare(str2)) {44 }45 46 // use str1 != str2 instead.47 if (0 != str1.compare(str2)) {48 }49 50 // Use str1 == "foo" instead.51 if (str1.compare("foo") == 0) {52 }53 54The above code examples show the list of if-statements that this check will55give a warning for. All of them use ``compare`` to check equality or56inequality of two strings instead of using the correct operators.57 58Options59-------60 61.. option:: StringLikeClasses62 63 A string containing semicolon-separated names of string-like classes.64 By default contains only ``::std::basic_string``65 and ``::std::basic_string_view``. If a class from this list has66 a ``compare`` method similar to that of ``std::string``, it will be checked67 in the same way.68 69Example70^^^^^^^71 72.. code-block:: c++73 74 struct CustomString {75 public:76 int compare (const CustomString& other) const;77 }78 79 CustomString str1;80 CustomString str2;81 82 // use str1 != str2 instead.83 if (str1.compare(str2)) {84 }85 86If `StringLikeClasses` contains ``CustomString``, the check will suggest87replacing ``compare`` with equality operator.88