Saturday, March 10, 2007

Be careful with STL strings

Please refer to the following C++ code fragment:
    char charArray[4]={'a','b','c',0,};
string str1(charArray);
string str2;
str2.append(charArray, 4);
Use the following lines to print out the contents of str1 and str2:
    cout << "str1 [" << str1 << ']' << endl;
cout << "str2 [" << str2 << ']' << endl;
The output would be:
str1 [abc]
str2 [abc]
Two strings looks same. However, does str1 equal to str2?
    cout << (str1 == str2? "equal" : "not equal") << endl;
The output:
not equal
Why not!? Let's print out the size of the strings:
    cout << "str1 size = " << str1.size() << endl;
cout << "str2 size = " << str2.size() << endl;
The output:
str1 size = 3
str2 size = 4
In short, we should be careful about the == operator of strings. It does not only compare the contents of strings, but it also compares the size of strings.

No comments: