strcpy与strncpy

strcpy:

函数原型:

char *strcpy(char *dest, const char* src) ;------将src中包括null的字符串复制到dest所指向的内存中,返回dest指针

所需头文件#include <string>

实现方式:

char *strcpy(char *dest, const char* src)
{
	assert(dest != NULL && src != NULL) ;
	char *str = dest ;
	while((*str++ = *src++) != '\0') ;
	return dest ;
}

例1:

#include <string>
#include <iostream>
using namespace std ;
int main()
{
	char dest[] = "hello, i am!" ;
	char source[] = "abc" ;
	strcpy(dest, source) ;
	printf("%s\n", dest) ;
	for (int i = 0; i < sizeof(dest) ; ++i)
		cout <<dest[i] ;
	system("pause") ;
	return 0 ;
}
输出结果:

可以看出他是把'\0'也复制过去了


strncpy:

函数原型:char * strncpy(char *dest, char *src, size_t num);

功能:会将src中的num个字符复制到dest,如果中途要到'\0'字符,则会填充'\0'字符

如:

#include <string>
#include <iostream>
using namespace std ;
int main()
{
	char dest[] = "hello, i am!" ;
	char source[] = "a\0def" ;
	strncpy(dest, source, 5) ;
	printf("%s\n", dest) ;
	for (int i = 0; i < sizeof(dest) ; ++i)
		cout <<dest[i] ;
	system("pause") ;
	return 0 ;
}
其运行结果如下:

例:

#include <string>
#include <iostream>
using namespace std ;
int main()
{


	char* source="how are you ?";
	char dest[20]="ABCDEFGHIJKLMNOPQRS";
	strcpy(dest,source); //
	strncpy(dest, source, sizeof(dest));//
	printf("%s\n", dest) ;
	for (int i = 0; i < sizeof(dest) ; ++i)
		cout <<dest[i] ;
	system("pause") ;
	return 0 ;
}
当语句是strcpy(dest, source) ;时输出是:
看来他是不填充'\0'的

当语句是strncpy(dest, source, sizeof(dest)) ;输出:

此时会填充'\0'

例:

#include <string>
#include <iostream>
using namespace std ;
int main()
{
	char* source="how are you ?";
	char dest[10];
	//strcpy(dest,source); //此时会内存溢出
	strncpy(dest, source, sizeof(dest));//此时可以但目标字符串没有'\0'字符,需要我们自己加上'\0'字符
	dest[sizeof(dest) - 1] = '\0' ;
	printf("%s\n", dest) ;
	for (int i = 0; i < sizeof(dest) ; ++i)
		cout <<dest[i] ;
	system("pause") ;
	return 0 ;
}
对于src大于dest时需要手动加上'\0'结束符否则出现:

加上就行了,但会漏掉一些字符,所以适合str小于dest的情况.





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值