字符串
定义:
字符串是一个或多个字符序列。
说明:
- 在C语言中,字符串存储在char类型的数组中。
- 存储字符串时,数组中字符串尾以空字符 \0 结束
- 双引号为字符串,单引号为单个字符。
例如:
"hello world!"
h | e | l | l | o | w | o | r | l | d | ! | \0 |
空字符:不是数字0,是非打印字符,ASCLL码值为0.
声明&赋值&初始化
char 变量名 [存储大小] ;
char str1[10]; //声明
str1="hello!"; //赋值
char str2[]="world"; //初始化 1.0
char str3[]={'w','o','r','l','d'}; //2.0
char str4[10]={'w','o','r','l','d'}; //3.0
#include<stdio.h>
int main()
{
char str[]="hello world!";
printf("%s",str); //通过%s转换说明,打印字符串
return 0;
}
应用
#include<stdio.h>
int main()
{
char s[10]="hello";
char name[30];
printf("输入你的名字:\n");
scanf("%s",name);
printf("%s %s",s,name);
return 0;
}
常用函数:
strlen:返回字符串的字符数量。(不会计入空字符)
以 \0 为结束标记
#include<stdio.h>
#include<string.h>
int main()
{
char a[]="123456";
char b[]={'1','2','\0','3','4'}; //以\0 为结束
char c[]={'1','2','3'}; //随机值
printf("a---%d\n",strlen(a));
printf("a---%d\n",strlen(b));
printf("a---%d\n",strlen(c));
return 0;
}
练习:
\0 空字符:是非打印字符,ASCLL码值为0.
#include<stdio.h>
int main()
{
char c[300];
for(int i=0;i<300;i++)
{
c[i]=i;
}
printf("%d",strlen(c));
}
char 0~127 -128~-1 0~44
i 0~127 128~255 256~300
输出:
0
最难不过坚持!