1. 字符数组初始化传递
字符数组的定义方法与上一节的一维数组类型相似
#include <stdio.h>
void main(){
char c[10];
}
字符数组初始化
#include <stdio.h>
void main(){
// char c[5]={'h','e','l','l','o'}; // 不建议这么写
char c[5]="hello";
printf("%s\n", c); // 会打印乱码
}
报错原因:因为printf通过%s打印字符串是会一次输出每一个字符,当到结束符'\0'时结束
2. scanf读取字符串
错误写法:
#include <stdio.h>
void main(){
char c[11];
scanf("%s",c); // 假设输入 hello world
printf("%s\n",c); // 只会输出 hello
}
原因:scanf通过"%s"读取字符串时,会忽略【空格】和【回车】
正确写法:
#include <stdio.h>
void main(){
char c[10];
char d[10];
scanf("%s%s",c,d); // 假设输入 hello world
printf("%s %s\n",c,d); // 只会输出 hello
}
3. gets函数和puts函数
gets函数:
类似于scanf函数,用于读取标准输入,
特点:
· 可以一次读一行字符串
· 自动输入一个"\0"结数符
· 与scanf的区别是scanf遇到【空格】后不存储,gets遇到【回车\n】不存储
#include <stdio.h>
void main(){
char c[20];
// gets函数中放入字符数组的数组名
gets(c); // 假设输入 hello world
// puts函数中放入字符数组的数组名
puts(c); // 输出 hello world
}
puts函数:
类似于printf函数,用于标准输出,
特点:
· 只能输出字符
· 多输入一个换行符等价于printf("%s\n")
4. str系列字符串造作函数
#include <stdio.h>
#include <string.h>
void main(){
int len;
char c[20];
char d[100]="world";
gets(c); // 假设输入 hello
puts(c); // 输出 hello
len = strlen(c); // 获取c的长度
printf("len=%d\n",len); // 输出 len=5
// 把 d 拼接到 c中
strcat(c,d);
puts(c); // 输出 helloworld
char e[100];
// 把 c 复制给 e;
strcpy(e,c);
puts(e); // helloworld
// 比较字符串大小
printf("c?e=%d\n", strcmp(c,e)); // 相等时是 0;
printf("c?d=%d\n", strcmp(c,d)); // 小于时是负值;
printf("d?c=%d\n", strcmp(d,c)); // 大于时是正值;
}