The compare trap example for std::string is explained in C and C++

  • 2020-06-01 10:22:28
  • OfStack


C++ language is a 10 point excellent language, but excellent does not mean perfect. There are still a lot of people who don't want to use C or C++, why? One of the reasons is that C/C++ text processing is too cumbersome to use. When I haven't been exposed to other languages before, whenever people say this, I always dismiss them as not understanding the essence of C++, or not understanding C++ at all. Now after I touch perl, php, and Shell script, I begin to understand why some people say C++ text processing is inconvenient.

In a word, with string, C++ 's character text processing function has finally been supplemented. In addition, STL' s text processing function has been greatly reduced compared with perl, shell and php when it is used with other containers of STL. So mastering string will make your job a lot easier.

string is simple to use

In fact, string is not a single container, just a single typedef of the basic_string template class, which corresponds to wstring. You will find the following code in the string header file:

extern "C++" {
typedef basic_string <char> string;
typedef basic_string <wchar_t> wstring;
} // extern "C++"

Since it only explains the use of string, this article does not distinguish between string and basic_string without special instructions.

string is really equivalent to a sequence container for holding characters, so in addition to the usual operations of a string, there are also operations that contain all sequence containers. Common string operations include: add, delete, modify, find comparison, link, input, output, and so on.

Without further ado, take a look at the body of this article.


1.std::string is often used to store string data, but it can also be used as byte storage for any byte.

2. Normally we use the compare method of std::string to compare strings, but this method is not reliable for comparing strings.

instructions method is not the same as strcmp method std::string size() All the bytes in size size() In the length range, if there is a '\0' character, it is better to convert it to if you do not know whether std::string stores pure strings or not const char* (调用c_str()) , then call strcmp comparison. The pit is still scary.


1. The following example is a good example of why compare is not appropriate when comparing strings.

#include <string>
#include <iostream>
#include <string.h>

int main(int argc, char const *argv[]){
 std::string str("hello");

 std::cout << str.size() << std::endl;
 std::cout << str << std::endl;
 std::cout <<"hello") << std::endl;
 std::cout << strcmp(str.c_str(),"hello") << std::endl;

 return 0;


$ ./test-string.exe


Related articles: