Comparing strings

The following allocates two string buffers and it calls the strcpy_s function to initialize each with the same string:

    char p1[6]; 
strcpy_s(p1, 6, "hello");
char p2[6];
strcpy_s(p2, 6, p1);
bool b = (p1 == p2);

The strcpy_c function will copy characters from the pointer given in the last parameter (until the terminating NUL), into the buffer given in the first parameter, whose maximum size is given in the second parameter. These two pointers are compared in the final line, and this will return a value of false. The problem is that the compare function is comparing the values of the pointers, not what the pointers point to. The two buffers have the same string, but the pointers are different, so b will be false.

The correct way to compare strings is to compare the data character by character to see if they are equal. The C runtime provides strcmp that compares two string buffers character by character, and the std::string class defines a function called compare that will also perform such a comparison; however, be wary of the value returned from these functions:

    string s1("string"); 
string s2("string");
int result = s1.compare(s2);

The return value is not a bool type indicating if the two strings are the same; it is an int. These compare functions carry out a lexicographical compare and return a negative value if the parameter (s2 in this code) is greater than the operand (s1) lexicographically, and a positive number if the operand is greater than the parameter. If the two strings are the same, the function returns 0. Remember that a bool is false for a value of 0 and true for non-zero values. The standard library provides an overload for the == operator for std::string, so it is safe to write code like this:

    if (s1 == s2) 
{
cout << "strings are the same" << endl;
}

The operator will compare the strings contained in the two variables.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset