Joining or concatenating two strings is another fundamental string operation, and the C-string library implements the operation with the strcat function. strcat is similar to the strcpy function, but requires offsetting the destination index during the copy operation.
strcat: String-Concatenation
strcat(s1, s2)
strcat function concatenates two C-strings by appending the source (the second parameter) to the end of the destination (the first parameter). It is essential that the destination, s1, is initialized before calling strcat and refers to a contiguous block of memory large enough to hold both strings. If the destination is an empty string (i.e., it does not contain any text), the program must null-terminate it before the concatenation operation.
#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);
|
char s1[15];
char s2[15] = { "Hello world" };
strcat(s1, s2);
|
| (a) | (b) | (c) |
| 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))
;
while (*(s++) = *(source++))
;
return dest;
} |
| (a) | (b) |
char s1[100] = "Hello "; char s2[100] = "world"; |
0123456 s1: Hello s2: world |
while (*s) s++;