Append characters from string
# include <string.h> char * strncat(char * dest, const char * src, int count);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.
上述内容是C++官网对strncat函数的介绍,与strcat函数不同的是,如果源字符串的长度小于count,则只复制到'\0'之前的内容。 (ps:strcat函数实现)
接下来给出实现strncat函数的源代码:
#define _CRT_SECURE_NO_WARNINGS 1 /* * Copyright (c) 2018, code farmer from sust * All rights reserved. * * 文件名称:MyStrcat.c * 功能:实现库函数strcat * char * strncat (char * destination, const char * source, int count) * * 当前版本:V1.0 * 作者:sustzc * 完成日期:2018年5月6日17:15:44 */ # include <stdio.h> # include <assert.h> /* * 函数名称:MyStrncat * * 函数功能:将源字符串的内容连接到目标字符串后面, * 目标字符串中的终止空字符被源字符串的第一个字符覆盖, * 新字符串的末尾包含一个空字符。 * * 入口参数:dest, src, count * * 出口参数:dest * * 返回类型:char * */ char * MyStrncat(char * dest, const char * src, int count) { char * cp = dest; assert((NULL != src) && (NULL != cp)); while ('\0' != *cp) { cp++; } while (count--) { if (!(*cp++ = *src++)) { return dest; } else { *cp = '\0'; } } return dest; } int main(void) { char str1[10] = "abcd"; char str2[10] = "123456789"; printf("str1: %s\n", str1); printf("str2: %s\n", str2); printf("connect after,str1: %s\n", MyStrncat(str1, str2, 5)); return 0; }
输出结果