测试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