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.
strcat: String-Concatenation
strcat(s1, s2)
strcat function concatenates two C-strings by appending the source (the second argument) to the end of the destination (the first argument). It is essential that the destination, s1, is initialized before calling strcat. If the destination is an empty string (i.e., it does not contain any text), the program must null terminate it (see Figure 2 (b) and (c)).
#include <cstring>char* strcat(char* destination, const char* source);errno_t strcat_s(char* dest, size_t size, const char* source);
char* s1;
char s2[15] = { "Hello world" };
strcat(s1, s2);
|
char s1[5];
char s2[15] = { "Hello world" };
strcat(s1, s2);
|
| (a) | (b) |
char* does not allocate memory to store the copied C-string, and s1 is not initialized with a null termination character.strcat function does require s1 to have a null termination character. See Figure 4 below.
| Standard Version | Microsoft Version |
|---|---|
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <cstring>
using namespace std;
int main()
{
char s1[100] = "HELLO";
char* s2 = " WORLD";
cout << strcat(s1, s2) << endl;
cout << s1 << endl;
return 0;
} |
#include <iostream>
#include <cstring>
using namespace std;
int main()
{
char s1[100] = "HELLO";
char* s2 = " WORLD";
cout << strcat(s1, 100, s2) << endl;
cout << s1 << endl;
return 0;
}
|
| Output: | |
HELLO WORLD HELLO WORLD |
0 HELLO WORLD |
| (a) | (b) |
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <cstring>
using namespace std;
int main()
{
char s1[100] = "";
char* s2 = "see ";
char* s3 = "the ";
char* s4 = "quick ";
char* s5 = "red ";
char* s6 = "fox";
strcat(s1, s2);
strcat(s1, s3);
strcat(s1, s4);
strcat(s1, s5);
strcat(s1, s6);
cout << s1 << endl;
return 0;
}
Output:
see the quick red fox
char s1[100]; s1[0] = '\0';
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;
} |