strncpy()函数类似于strcpy()函数,不同之处在于它只从源字符串复制指定数量的字符到目标字符串。
C strncpy()声明
char *strncpy(char *str1, const char *str2, size_t n)
str1 - 目标字符串。复制源字符串str2的前n个字符到其中的字符串。
str2 - 源字符串
`n - 需要复制的源字符串的字符数。
strncpy()的返回值
在将源字符串的n个字符复制到其中之后,它返回指向目标字符串的指针。
示例:strncpy()函数
#include <stdio.h>#include <string.h>int main () {char str1[20];char str2[25];/* The first argument in the function is destination string.* In this case we are doing full copy using the strcpy() function.* Here string str2 is destination string in which we are copying the* specified string*/strcpy(str2, "welcome to beginnersbook.com");/* In this case we are doing a limited copy using the strncpy()* function. We are copying only the 7 characters of string str2 to str1*/strncpy(str1, str2, 7);printf("String str1: %s\n", str1);printf("String str2: %s\n", str2);return 0;}
输出:
String str1: welcomeString str2: welcome to beginnersbook.com
