C语言之strncpy函数

【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;
}



  • 2
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值