The Java String class provides a method, concat, that concatenates or appends one String object to another, and two concatenation operators: + and +=. While C++ also provides a strcat function. However, the results are meaningless when C++ programmers use the operators despite compiling without error. Like the assignment operator, these operators operate on the C-strings' addresses, not their contents. The behavior of the C++ strcat function is very similar to Java's method or += operator.
The strcat function. The string-concatenate function concatenates two C-strings by appending its second argument to its first. The program passes both arguments to the function by pointer, but the second argument is const and can't be modified. The standard and Microsoft versions return the concatenated string through the first argument. Notice the space before the 'W' in s2.
The standard version also returns s1 as the return value, making the concatenated C-strings available a second way.
The Microsoft version returns an error condition: 0 when the function succeeds and non-0 when it fails.
Possible Implementations
char* strcat(char* dest, const char* source)
{
size_t size = strlen(dest);
for (size_t i = 0; i <= strlen(source); i++)
dest[size + i] = source[i];
return dest;
}
char* strcat(char* dest, const char* source)
{
char* s = dest;
while (*(s))
s++;
while (*(s++) = *(source++))
;
return dest;
}
Two implementations of the standard strcat function. You must learn how to read and understand program code. To help develop that skill, study the two implementations of the strcpy function presented in the previous section. Study the elaborations following the functions, including the review links. Describe (to yourself) how these functions work after studying the strcpy function and the previous corresponding examples.
Your elaborations don't need to be as formal or extensive as the examples but focus on understanding the code. For each function statement, ask yourself the following elaboration questions:
What does the statement do?
How does the statement connect to the problem of concatenating strings?
How does the statement help to concatenate the strings?