【C】库函数之 strcat

目录

1. Concatenate strings

2. 源代码

3. 输出结果


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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值