📘字符数组

2026-09-04
⭐⭐ GESP 4级

📖概念讲解

字符数组就是用 char 类型的数组来存储字符串。C++ 中字符串本质是以 '\0'(空字符)结尾的字符数组,这个 '\0' 是字符串的结束标志,占用一个字节但不参与输出。

和 string 类不同,字符数组需要你手动管理空间和结束符。它的优势是底层、高效、适合算法竞赛中处理字符操作。

💡 核心要点:
  • 声明时要多留一位给 '\0',比如存 "hello" 需要 char s[6] 而不是 char s[5]
  • strlen() 返回的是不计 '\0' 的实际长度,sizeof 返回数组总字节数
  • cin >> s 遇到空格/回车就停,读整行要用 cin.getline() 或 getline()

💻代码示例

1#include <iostream>
2#include <cstring> // strlen, strcpy, strcat, strcmp
3using namespace std;
4
5int main() {
6 // 1. 声明和初始化字符数组
7 char s1[6] = "hello"; // 自动补 '\0',实际存 h,e,l,l,o,\0
8 char s2[] = "world"; // 编译器自动算大小 = 6
9
10 // 2. strlen vs sizeof
11 cout << "strlen(s1)=" << strlen(s1) << endl; // 输出 5(不含 '\0')
12 cout << "sizeof(s1)=" << sizeof(s1) << endl; // 输出 6(包含 '\0')
13
14 // 3. 遍历字符数组
15 for (int i = 0; s1[i] != '\0'; i++) { // 逐字符遍历,到 '\0' 停止
16 cout << s1[i];
17 }
18 cout << endl;
19
20 // 4. 常用字符串函数
21 char dest[20];
22 strcpy(dest, s1); // 把 s1 复制到 dest
23 strcat(dest, s2); // 把 s2 拼接到 dest 后面
24 cout << dest << endl; // 输出 helloworld
25
26 // 5. strcmp 比较两个字符串(按字典序)
27 if (strcmp(s1, s2) < 0) { // 返回负数表示 s1 < s2
28 cout << "s1 排在 s2 前面" << endl;
29 }
30
31 return 0;
32}
33// 输出:
34// strlen(s1)=5
35// sizeof(s1)=6
36// hello
37// helloworld
38// s1 排在 s2 前面

🧩互动小测

Q1:声明 char s[] = "abc"; 后,sizeof(s) 等于多少?

Q2:以下哪个函数不能用来比较两个字符数组的内容?

Q3:执行 char a[10]; strcpy(a, "hello"); 后,strlen(a) 等于?

🏋️动手练一练

📝 编程练习

写一个程序,输入一个字符串(不超过100个字符),统计其中大写字母、小写字母、数字和其他字符的个数。

输入:一行字符串,可能包含空格
输出:四个整数,分别表示大写字母、小写字母、数字、其他字符的个数,空格分隔

提示:用 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;
}

要点:cin.getline(s, 101) 可以读入包含空格的整行;遍历时以 '\0' 作为结束条件;cctype 头文件提供了 isupper/islower/isdigit 等判断函数。

📝易错点提醒

学完这个知识点后点一下