1.. title:: clang-tidy - readability-string-compare 2 3readability-string-compare 4========================== 5 6Finds string comparisons using the compare method. 7 8A common mistake is to use the string's ``compare`` method instead of using the 9equality or inequality operators. The compare method is intended for sorting 10functions and thus returns a negative number, a positive number or 11zero depending on the lexicographical relationship between the strings compared. 12If an equality or inequality check can suffice, that is recommended. This is 13recommended to avoid the risk of incorrect interpretation of the return value 14and to simplify the code. The string equality and inequality operators can 15also be faster than the ``compare`` method due to early termination. 16 17Example 18------- 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 will 55give a warning for. All of them use ``compare`` to check equality or 56inequality of two strings instead of using the correct operators. 57 58Options 59------- 60 61.. option:: StringLikeClasses 62 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 has 66 a ``compare`` method similar to that of ``std::string``, it will be checked 67 in the same way. 68 69Example 70^^^^^^^ 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 suggest 87replacing ``compare`` with equality operator. 88