·字符串
·使用字符型数组存储
·每个存储单元占一个字节
·以空字符结尾
·注意空字符不要和NULL混淆
·空字符是字符串的终止符
·NULL是一个符号,表示不引用任何内容的内存地址
·定义字符串的几种方式
//**************************************************************************************program
#include <stdio.h>
#include <stdlib.h>
int main()
{
//定义字符串的几种方式
//字符串和字符数组的区别:最后一位是否是空字符
char names1[] = {'j','a','c','k','\0'};//如果没有'\0',那么定义的就不是字符串,是字符型数组
char names2[] = "jack";
char *names3 = "jack";
printf("数组所占空间大小:%d\n",sizeof(names1));//结果是5,因为有一个是空字符
printf("数组所占空间大小:%d\n",sizeof(names2));//结果是5,因为有一个是空字符
printf("数组所占空间大小:%d\n",sizeof(*names3));//结果是1
return 0;
}
//**************************************************************************************program
·字符串的动态输入方式
//**************************************************************************************program
#include <stdio.h>
#include <stdlib.h>
int main()
{
char names2[50];
printf("请输入新名称:");
scanf("%s", names2);//数组名本来就是一个地址,所以不需要“&”了
printf("%s\n", names2);
return 0;
}
//**************************************************************************************program
·get puts函数补充
·只能获得字符串
·gets(names2);//scanf("%s", names2);
·注意:gets函数不对接受字符串的buffer进行边界监测,会造成越界,从而产生bug
·改进可以用fgets(#include <string.h>)
·fgets(names2, 10, stdin);//从标准输入流(标准的input)中读取10个字节(10-1个数字+‘\n’)到names2
·只能输出字符串
puts(names2);//printf("%s\n", names2);
·随堂练习
·书写函数,返回传入字符串的长度
·分别使用gets函数和fgets函数
//**************************************************************************************program
#include <stdio.h>
#include <stdlib.h>
//返回传入字符串的长度
int GetStrLength(char[]);
int GetStrLength(char str[])
{
int count = 0; //字符串中字符的个数
while(str[count] != '\0')
{
if(str[count] == '\n') //将‘\n’替换成‘\0’
{
str[count] == '\n';
break;
}
count++;
}
return count;
}
int main()
{
char names1[] = {'j','a','c','k','\0'};
// fgets(names1,5,stdin); 这样打印的结果会多一个\n,输入abc,显示长度4
int len = GetStrLength(names1);
printf("字符串的长度为:%d\n", len);//长度4
return 0;
}
//**************************************************************************************program
C语言第64+65课初识字符串与字符数组
最新推荐文章于 2023-07-07 16:22:51 发布