字符数组就是用 char 类型的数组来存储字符串。C++ 中字符串本质是以 '\0'(空字符)结尾的字符数组,这个 '\0' 是字符串的结束标志,占用一个字节但不参与输出。
和 string 类不同,字符数组需要你手动管理空间和结束符。它的优势是底层、高效、适合算法竞赛中处理字符操作。
'\0',比如存 "hello" 需要 char s[6] 而不是 char s[5]strlen() 返回的是不计 '\0' 的实际长度,sizeof 返回数组总字节数cin >> s 遇到空格/回车就停,读整行要用 cin.getline() 或 getline()char s[] = "abc"; 后,sizeof(s) 等于多少?char a[10]; strcpy(a, "hello"); 后,strlen(a) 等于?cin.getline() 读取含空格的整行,用 isupper()、islower()、isdigit() 判断字符类型。
#include <iostream>
#include <cstring>
#include <cctype>
using namespace std;
int main() {
char s[101];
cin.getline(s, 101); // 读整行(含空格)
int upper = 0, lower = 0, digit = 0, other = 0;
for (int i = 0; s[i] != '\0'; i++) { // 逐字符遍历
if (isupper(s[i])) upper++; // 大写字母
else if (islower(s[i])) lower++; // 小写字母
else if (isdigit(s[i])) digit++; // 数字
else other++; // 其他字符
}
cout << upper << " " << lower << " " << digit << " " << other << endl;
return 0;
}
char s[5] = "hello"; 会越界!"hello" 需要 6 个字节(5个字符 + '\0')char a[]="hi", b[]="hi"; a==b 比较的是地址而非内容,永远不等!用 strcmp(a,b)==0cin.getline(s, 大小)strcpy 不检查目标数组大小,目标太小会栈溢出,这是安全隐患char s[10]; s = "abc"; 编译报错!要用 strcpy(s, "abc")