目录
1. Append characters from string
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