【C】库函数之 strncat

目录

1. Append characters from string

2. 源代码

3. 输出结果


1. Append characters from string

#include <string.h>
char * strncat ( char * destination, const char * source, size_t num );

Appends the first num characters of source to destination, plus a terminating null-character.

If the length of the C string in source is less than num, only the content up to the terminating null-character is copied.

上述内容是 cplusplus 对 strncat 函数的介绍,

与 strcat 函数不同的是,如果源字符串的长度小于 count,则只复制到 '\0' 之前的内容。(ps:strcat函数实现

2. 源代码

#include <stdio.h>
#include <assert.h>                                                                                                                                     
#include <string.h>
 
#define MAX_CAT_CNT 5
 
#if 0
char *Strncat(char *dest, const char *src, size_t n) {
    assert((NULL != src) && (NULL != dest));
 
    char *ret = dest;
 
    while ('\0' != *ret)
        ++ret;
 
    while ((n--) && ('\0' != ((*ret++) = (*src++))))
        ;
 
    return dest;
}
#endif

char *Strncat(char *dest, const char *src, size_t n) {
    assert((NULL != src) && (NULL != dest));
 
    size_t i = 0, dest_len = strlen(dest);
 
    for (; (i < n) && ('\0' != src[i]); ++i) {
        dest[dest_len + i] = src[i];
    }
 
    dest[dest_len + i] = '\0';
 
    return dest;
}
 
void test() {
    char str1[10] = "abc";
    char str2[] = "xyz";
 
    printf("call Strncat before, str1: %s, str2: %s\n", str1, str2);
    printf("call Strncat %d bytes after, str1: %s, str2: %s\n", MAX_CAT_CNT, Strncat(str1, str2, MAX_CAT_CNT), str2);
}
 
int main(void) {
    test();
 
    return 0;
}

3. 输出结果

call Strncat before, str1: abc, str2: xyz
call Strncat 5 bytes after, str1: abcxyz, str2: xyz

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值