目录
1. Concatenate strings
#include <string.h>
char * strcat ( char * destination, const char * source );
Appends a copy of the source string to the destination string. The terminating null character in destination is overwritten by the first character of source, and a null-character is included at the end of the new string formed by the concatenation of both in destination.
destination and source shall not overlap.
上述内容是 cplusplus 对 strcat 函数的介绍,
可以看出 strcat 函数将源字符串的内容 拼接 到目标字符串后面,而目标字符串中的终止空字符被源字符串的第一个字符覆盖,新字符串的末尾包含一个空字符。
需要注意的是,目标字符串不能与源字符串重叠。
如果目标数组大小 小于 源字符串,也会 拼接字符串成功,但是这导致了缓冲区溢出,是不安全的,比较安全的实现是指定需要拼接的字符串的大小,可以参考 strncat函数实现。
2. 源代码
#include <stdio.h>
#include <assert.h>
char *Strcat(char *dest, const char *src) {
assert((NULL != src) && (NULL != dest));
char *ret = dest;
while ('\0' != *ret)
++ret;
while (((*ret++) = (*src++)))
;
return dest;
}
void test() {
char str1[10] = "abc";
char str2[] = "xyz";
printf("call Strcat before, str1: %s, str2: %s\n", str1, str2);
printf("call Strcat after, str1: %s, str2: %s\n", Strcat(str1, str2), str2);
}
int main(void) {
test();
return 0;
}
3. 输出结果
call Strcat before, str1: abc, str2: xyz
call Strcat after, str1: abcxyz, str2: xyz