Copy characters from string
# include <string.h> char * strncpy(char * dest, const char * src, int count);
Copies the first num characters of source to destination. If the end of the source C string (which is signaled by a null-character) is found before num characters have been copied, destination is padded with zeros until a total of num characters have been written to it.
上述内容是C++官网对strncpy函数的介绍,可以看出与strcpy函数不同的是,src指向的C字符串复制到dest所指向的数组中,复制的字符长度为count。如果src指向的字符串长度小于count,那么在dest指向的字符串后面追加'\0',直到满足本次复制的字符长度为count。(ps:strcpy函数实现)
接下来给出实现strncpy函数的源代码:
#define _CRT_SECURE_NO_WARNINGS 1 /* * Copyright (c) 2018, code farmer from sust * All rights reserved. * * 文件名称:MyStrncpy.c * 功能:实现库函数strncpy * char * strncpy (char * destination, const char * source, int count) * * 当前版本:V1.0 * 作者:sustzc * 完成日期:2018年5月6日17:06:53 */ # include <stdio.h> # include <assert.h> /* * 函数名称:MyStrncpy * * 函数功能:复制源字符串的内容 * 将src指向的C字符串复制到dest所指向的数组中,复制的字符长度为count。 * 如果src指向的字符串长度小于count,那么在dest指向的字符串后面追加'\0', * 直到满足本次复制的字符长度为count * * 入口参数:dest, src, count * * 出口参数:dest * * 返回类型:char * */ char * MyStrncpy(char * dest, const char * src, int count) { char * cp = dest; assert((NULL != src) && (NULL != cp)); while (count && (*cp++ = *src++)) { count--; } if (count) { while (--count) { *cp++ = '\0'; } } else { ; } return dest; } int main(void) { char str1[10] = "abcde"; char str2[5] = "1234"; printf("str1: %s\n", str1); printf("str2: %s\n", str2); printf("copy after,str1: %s\n", MyStrncpy(str1, str2, 5)); return 0; }
输出结果