测试strncpy与strcpy,strlen 与sizeof的区别

测试strncpy与strcpy,


strlen 与sizeof的区别

strlen(str),从头开始计数,遇到'\0'结束,sizeof 只与定义有关

常考题

#include <stdio.h>
#include <string.h>

void main()
{
	/*
	*	第一部分测试strcpy
	*/
	char str[10]="ABCDEFGHI";
	printf("before use strcpy  the str is %s and strlen is %d sizeof(str)=%d\n",str,strlen(str),sizeof(str));
	//复制字符串到str,从起始位置开始,复制完成后末尾添加'\0'	
	strcpy(str,"CCCC");
	printf("after use strcpy   the str is %s and strlen is %d sizeof(str)=%d\n",str,strlen(str),sizeof(str));
	int i=0;	
	for(i=0;i<10;i++)
	{
		printf("str[%d] is %c\n",i,str[i]);
	}
	strcpy(str,"BBB");
	printf("after use strcpy   the str is %s and strlen is %d sizeof(str)=%d\n",str,strlen(str),sizeof(str));
	strcpy(str,"A");
	printf("after use strcpy   the str is %s and strlen is %d sizeof(str)=%d\n\n\n",str,strlen(str),sizeof(str));
	
	/*
	*	第二部分测试strncpy
	*/	
	char str1[10]="ABCDEFGHI";
	printf("before use strncpy the str is %s and is %d sizeof(str)=%d\n",str1,strlen(str1),sizeof(str1));
	//复制字符串到str1,从起始位置开始,指定复制的长度,不足的长度字符串补充'\0'
	strncpy(str1,"CCC",5);
	printf("after use strncpy  the str is %s and is %d sizeof(str)=%d\n",str1,strlen(str1),sizeof(str1));
	for(i=0;i<10;i++)
	{
		printf("str1[%d] is %c\n",i,str1[i]);
	}

	strncpy(str1,"BB",2);
	printf("after use strncpy  the str is %s and is %d sizeof(str)=%d\n",str1,strlen(str1),sizeof(str1));
	strncpy(str1,"A",1);
	printf("after use strncpy  the str is %s and is %d sizeof(str)=%d\n",str1,strlen(str1),sizeof(str1));
}


结果如下:

before use strcpy  the str is ABCDEFGHI and strlen is 9 sizeof(str)=10
after use strcpy   the str is CCCC and strlen is 4 sizeof(str)=10
str[0] is C
str[1] is C
str[2] is C
str[3] is C
str[4] is 
str[5] is F
str[6] is G
str[7] is H
str[8] is I
str[9] is 
after use strcpy   the str is BBB and strlen is 3 sizeof(str)=10
after use strcpy   the str is A and strlen is 1 sizeof(str)=10


before use strncpy the str is ABCDEFGHI and is 9 sizeof(str)=10
after use strncpy  the str is CCC and is 3 sizeof(str)=10
str1[0] is C
str1[1] is C
str1[2] is C
str1[3] is 
str1[4] is 
str1[5] is F
str1[6] is G
str1[7] is H
str1[8] is I
str1[9] is 
after use strncpy  the str is BBC and is 3 sizeof(str)=10
after use strncpy  the str is ABC and is 3 sizeof(str)=10


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值