字符串标准库函数的使用
/*
字符串长度计算函数(strlen)
字符串对比函数(strcmp)
字符串拼接函数(strcat)
字符串复制函数(strcpy)
*/
#include <stdio.h>
#include <string.h>
int main()
{
char buff[128]="qwer";
char str[]="1234";
//字符串长度计算函数(strlen)
int len;
len=strlen(str);
printf("str的有效长度:%d\n",len);
printf("str所占字节数:%d\n\n",sizeof(str));
//字符串对比函数(strcmp)
if(strcmp(buff,str)==0)
{
printf("str与buff相同。\n\n");
}
else
{
printf("str与buff不相同。\n\n");
}
//字符串拼接函数(strcat)
printf("buff为:%s,str为:%s\n",buff,str);
strcat(buff,str);
printf("buff拼接str为:%s\n\n",buff);
//字符串复制函数(strcpy)
strcpy(buff,str);
printf("str复制到buff为:%s\n",buff);
}
编译结果
/*编译结果:
str的有效长度:4
str所占字节数:5
str与buff不相同。
buff为:qwer,str为:1234
buff拼接str为:qwer1234
str复制到buff为:1234
*/
结论
//结论:
/*
(1)strlen返回值是字符串的有效长度,字符串的实际长度是有效长度+'\0'
(2)strcmp有返回值:0代表相同,1代表不同。
(3)strcat(1,2)返回链接后的字符串,是将2接在1的后面。
(4)strcpy(1,2)成功返回复制的字符串,失败返回NULL。将2复制到1,且先把1清空,再复制。
*/