【FROM MSDN && 百科】
原型:char * strncpy(char *dest, char *src, size_t n);
#include<string.h>
功能:将字符串src中最多n个字符复制到字符数组dest中(它并不像strcpy一样只有遇到NULL才停止复制,而是多了一个条件停止,就是说如果复制到第n个字符还未遇到NULL,也一样停止),返回指向dest的指针。
The strncpy function copies the initialcount characters ofstrSource tostrDest and returnsstrDest. Ifcount is less than or equal to the length ofstrSource, a null character is not appended automatically to the copied string. If count is greater than the length ofstrSource, the destination string is padded with null characters up to lengthcount. The behavior ofstrncpy is undefined if the source and destination strings overlap.
总结:strcpy
如果源长>目标长,则将源长中等于目标长的字符拷贝到目标字符串
如果源长<目标长,则源长全部拷贝到目标字符串,不包括'\0'
这两句话不理解?
char *p="how are you ?";
char name[20]="ABCDEFGHIJKLMNOPQRS";
printf("%s\n",p);
printf("%s\n",name);
strcpy(name,p);
printf("%s\n",name);
strncpy
如果指定长>源长,则将源长全部拷贝到目标长,自动加上'\0'
如果指定长<源长,则将源长中按指定长度拷贝到目标字符串,不包括'\0'
如果指定长>目标长,error happen!
DEMO:实现自己的strncpy函数
#include <stdio.h>
#include <conio.h>
#include <string.h>
#include <assert.h>
char *mystrncpy(char *dest,const char *src,int n);
int main(void)
{
char a[20]="how";
char b[20]="what";
mystrncpy(a,b,8); //mystrncpy(a,b,4)这两种情况来高度程序
printf("%s\n",a);
getch();
return 0;
}
/*
1.当要拷贝的字符个数(size_t n)小于或等于strSour长度, strDest的最后不会加\0
2.当要拷贝的字符个数(size_t n)大于strSour长度,strDest最后会自动追加一个\0
*/
char *mystrncpy(char *dest,const char *src,int n)
{
char *strDest=dest;
assert((dest!=NULL)&&(src!=NULL));
while( n &&(*dest++=*src++)!='\0')
{
n--;
}
if (n)
{
while(--n)
{
*dest++='\0';
}
}
return strDest;
}