1.字符串本质上是一个字符数组char[],以\0为结束标志,初始化字符串的方式如下:
char str[]={‘h’,‘e’,‘l’,‘l’,‘o’,’\0’} //输出的是hello,\0是结束标志
char str[100]={‘h’,‘e’,‘l’,‘l’,‘o’} //输出的是hello,剩下的默认填0
char str[]=“hello” //编译器会自动在末尾加0
sizeof(str) //结果为6 要算上\0
strlen(str) //结果为5,不统计\0
注意:sizeof可以用做任何类型的参数,而strlen只能用作char类型,且遇到\0或0就停下来
sizeof的功能是返回字节的大小,而strlen返回的是字符串的长度。
sizeof是C语言关键字,也是求字节运算符
strlen是函数
2.对字符串进行处理
1)拷贝字符串
实现功能:已有字符串char *str=“hello world!”,现要将字符串str拷贝到char cp[100]中
法一:利用数组进行拷贝
void copy_char01(char *target,char *source)
{
int len=strlen(source);
for(int i=0;i<len;i++)
{
target[i]=source[i];
printf("%c",target[i]);
}
}
void text01()
{
char *str=“hello world!”;
char cp[100];
copy_char01(cp,str);
//copy_char02(cp,str);
}
法2:利用指针进行拷贝
void copy_char02(char *target,char *source)
{
while(*source!=’\0’)
{
*target=*source;
target++;source++;
printf("%c",*target);
}
}
void text01()
{
char *str=“hello world!”;
char cp[100];
//copy_char01(cp,str);
copy_char02(cp,str);
}
2)字符串反转
功能:
//字符串反转
void outchar(char*p)
{
int len=strlen§;
for(int i=0;i<len;i++)
{
printf("%c",p[i]);
}
}
void reverse01(char *p)
{
int len=strlen§;
for(int i=0;i<=len/2;i++)
{
char c;
c=p[i];
p[i]=p[len-i-1];
p[len-i-1]=c;
}
}
void text02()
{
char buf[]=“biaobiaodaren”;
reverse01(buf);
outchar(buf);
}