一、字符串的几种定义方式及输出
1.第一种方式
#include<stdio.h>
int main()
{
int i;
char str[5] = {
'a','b','c','d','e'};
for(i=0;i<sizeof(str)/sizeof(str[0]);i++){
printf("%c", str[i]);
}
return 0;
}
2.第二种方式
#include<stdio.h>
int main()
{
int i;
char str2[5] = "abcde";
for(i=0;i<sizeof(str2)/sizeof(str2[0]);i++){
printf("%c", str2[i]);
}
return 0;
}
3.第三种方式
#include<stdio.h>
int main()
{
int i;
char str3[] = "abcde"; //数组元素个数不写,会根据真实大小默认分配
for(i=0;i<sizeof(str3)/sizeof(str3[0]);i++){
printf("%c", str3[i]);
}
return 0;
}
4.第四种方式(推荐)
#include<stdio.h>
int main()
{
//数组名就是地址(大多数情况下)
char *pstr = "hello world";
printf("%s\n",pstr); //字符串用格式占位符%s表示
return 0;
}
二、字符串的存储方式
字符串在内存中,除了有效字符以外,还会自动在后面补一个‘\0’,作为字符串的结束标志
三、计算字符串中字符的个数(strlen)
#include<stdio.h>