What is the difference between comparing strings using == and compare() in C++?
Hello colleagues! I started learning C++ and encountered a confusing situation. When I compare strings, I usually use the `==` operator, and it seems to work. But in other people's code, I often see the `compare()` method. Here's an example:\n\n```cpp\n#include \n#include \n\nint main() {\n std::string str1 = "Hello";\n std::string str2 = "Hello";\n std::string str3 = "World";\n\n // Method 1: == operator\n if (str1 == str2) {\n std::cout << "str1 == str2: true" << std::endl;\n }\n\n // Method 2: compare() method\n if (str1.compare(str2) == 0) {\n std::cout << "str1.compare(str2) == 0: true" << std::endl;\n }\n\n if (str1.compare(str3) != 0) {\n std::cout << "str1.compare(str3) != 0: true" << std::endl;\n }\n\n return 0;\n}\n```\n\nBoth methods
No answers yet.
Log in to leave an answer