C++ 从入门到精通C++ 从入门到精通
首页
基础教程
进阶教程
实战项目
编程指南
首页
基础教程
进阶教程
实战项目
编程指南
  • 🚀 C++ 基础入门

    • 📚 C++ 基础教程
    • 第1章 - 环境搭建和第一个程序
    • 第2章 - 变量和数据类型
    • 第3章 - 输入输出和运算符
    • 第4章 - 条件判断
    • 第5章 - 循环语句
    • 第6章 - 函数基础
    • 第7章 - 数组和字符串

第7章 - 数组和字符串

嗨,朋友!我是长安。

到目前为止,我们学会的变量都只能存储一个值。但在实际开发中,我们经常需要处理一组数据,比如:

  • 一个班级所有学生的成绩
  • 一周7天的温度
  • 一个句子中的所有字符

这一章,我要教你如何使用数组和字符串来处理这些数据!

🤔 什么是数组?

生活中的例子

想象你有一个鸡蛋盒:

[鸡蛋1] [鸡蛋2] [鸡蛋3] [鸡蛋4] [鸡蛋5] [鸡蛋6]
   0       1       2       3       4       5
  • 鸡蛋盒就是数组
  • 每个格子就是数组元素
  • 格子的编号(0、1、2...)就是下标/索引

编程中的数组

数组是一组相同类型数据的集合,存储在连续的内存空间中。

特点:

  • ✅ 存储多个相同类型的数据
  • ✅ 通过下标访问元素
  • ✅ 下标从 0 开始
  • ✅ 大小固定,定义后不能改变

📦 定义和使用数组

基本格式

数据类型 数组名[数组大小];

示例1:定义数组

#include <iostream>
using namespace std;

int main() {
    // 定义一个可以存储5个整数的数组
    int scores[5];
    
    // 给数组元素赋值
    scores[0] = 90;
    scores[1] = 85;
    scores[2] = 92;
    scores[3] = 88;
    scores[4] = 95;
    
    // 访问数组元素
    cout << "第1个成绩:" << scores[0] << endl;
    cout << "第2个成绩:" << scores[1] << endl;
    cout << "第3个成绩:" << scores[2] << endl;
    cout << "第4个成绩:" << scores[3] << endl;
    cout << "第5个成绩:" << scores[4] << endl;
    
    return 0;
}

输出:

第1个成绩:90
第2个成绩:85
第3个成绩:92
第4个成绩:88
第5个成绩:95

注意

数组下标从 0 开始!

int arr[5];  // 定义一个大小为5的数组
// 有效下标:0, 1, 2, 3, 4
// 无效下标:5(会越界)

示例2:数组初始化

#include <iostream>
using namespace std;

int main() {
    // 方法1:定义时初始化
    int arr1[5] = {10, 20, 30, 40, 50};
    
    // 方法2:部分初始化(其余为0)
    int arr2[5] = {1, 2};  // {1, 2, 0, 0, 0}
    
    // 方法3:全部初始化为0
    int arr3[5] = {0};
    
    // 方法4:省略大小(自动推断)
    int arr4[] = {100, 200, 300};  // 大小为3
    
    // 输出arr1
    cout << "arr1: ";
    for (int i = 0; i < 5; i++) {
        cout << arr1[i] << " ";
    }
    cout << endl;
    
    return 0;
}

🔄 遍历数组

使用循环可以方便地访问数组中的所有元素。

示例1:计算总分和平均分

#include <iostream>
using namespace std;

int main() {
    int scores[5] = {90, 85, 92, 88, 95};
    int sum = 0;
    
    // 遍历数组计算总分
    for (int i = 0; i < 5; i++) {
        sum += scores[i];
    }
    
    double average = sum / 5.0;
    
    cout << "总分:" << sum << endl;
    cout << "平均分:" << average << endl;
    
    return 0;
}

输出:

总分:450
平均分:90

示例2:查找最大值和最小值

#include <iostream>
using namespace std;

int main() {
    int numbers[8] = {45, 23, 67, 89, 12, 56, 34, 78};
    int maxNum = numbers[0];
    int minNum = numbers[0];
    
    for (int i = 1; i < 8; i++) {
        if (numbers[i] > maxNum) {
            maxNum = numbers[i];
        }
        if (numbers[i] < minNum) {
            minNum = numbers[i];
        }
    }
    
    cout << "最大值:" << maxNum << endl;
    cout << "最小值:" << minNum << endl;
    
    return 0;
}

输出:

最大值:89
最小值:12

示例3:数组反转

#include <iostream>
using namespace std;

int main() {
    int arr[5] = {1, 2, 3, 4, 5};
    
    cout << "原数组:";
    for (int i = 0; i < 5; i++) {
        cout << arr[i] << " ";
    }
    cout << endl;
    
    // 反转数组
    for (int i = 0; i < 5 / 2; i++) {
        int temp = arr[i];
        arr[i] = arr[5 - 1 - i];
        arr[5 - 1 - i] = temp;
    }
    
    cout << "反转后:";
    for (int i = 0; i < 5; i++) {
        cout << arr[i] << " ";
    }
    cout << endl;
    
    return 0;
}

输出:

原数组:1 2 3 4 5
反转后:5 4 3 2 1

📝 字符串(C风格)

在 C++ 中,字符串可以用字符数组表示。

示例1:定义字符串

#include <iostream>
using namespace std;

int main() {
    // 方法1:字符数组
    char str1[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
    
    // 方法2:直接初始化(自动添加\0)
    char str2[] = "Hello";
    
    // 方法3:指定大小
    char str3[20] = "World";
    
    cout << str1 << endl;
    cout << str2 << endl;
    cout << str3 << endl;
    
    return 0;
}

输出:

Hello
Hello
World

字符串结束符

C风格字符串必须以 \0(空字符)结尾,表示字符串结束。

char str[] = "Hello";
// 实际存储:'H' 'e' 'l' 'l' 'o' '\0'

🎯 string 类(推荐)

C++ 提供了更强大的 string 类,使用更方便。

基本用法

#include <iostream>
#include <string>
using namespace std;

int main() {
    // 定义字符串
    string name = "张三";
    string greeting = "你好";
    
    // 字符串拼接
    string message = greeting + "," + name + "!";
    cout << message << endl;
    
    // 获取字符串长度
    cout << "字符串长度:" << message.length() << endl;
    
    // 访问单个字符
    cout << "第一个字符:" << message[0] << endl;
    
    return 0;
}

输出:

你好,张三!
字符串长度:11
第一个字符:你

常用字符串操作

#include <iostream>
#include <string>
using namespace std;

int main() {
    string str = "Hello World";
    
    // 获取长度
    cout << "长度:" << str.length() << endl;
    
    // 获取子串
    string sub = str.substr(0, 5);  // 从位置0开始,取5个字符
    cout << "子串:" << sub << endl;
    
    // 查找字符串
    int pos = str.find("World");
    cout << "World 的位置:" << pos << endl;
    
    // 替换
    str.replace(6, 5, "C++");  // 从位置6开始,替换5个字符
    cout << "替换后:" << str << endl;
    
    // 清空
    str.clear();
    cout << "清空后是否为空:" << (str.empty() ? "是" : "否") << endl;
    
    return 0;
}

输出:

长度:11
子串:Hello
World 的位置:6
替换后:Hello C++
清空后是否为空:是

字符串输入

#include <iostream>
#include <string>
using namespace std;

int main() {
    string name, sentence;
    
    // cin >> 读取一个单词(遇到空格停止)
    cout << "请输入你的名字:";
    cin >> name;
    
    // getline() 读取一整行(包括空格)
    cin.ignore();  // 清除缓冲区的换行符
    cout << "请输入一句话:";
    getline(cin, sentence);
    
    cout << "\n名字:" << name << endl;
    cout << "句子:" << sentence << endl;
    
    return 0;
}

🌟 实战案例

案例1:成绩统计系统

#include <iostream>
using namespace std;

int main() {
    const int SIZE = 5;
    double scores[SIZE];
    double sum = 0;
    double maxScore = 0;
    double minScore = 100;
    
    // 输入成绩
    cout << "请输入" << SIZE << "个学生的成绩:" << endl;
    for (int i = 0; i < SIZE; i++) {
        cout << "第" << (i + 1) << "个学生:";
        cin >> scores[i];
        
        sum += scores[i];
        
        if (scores[i] > maxScore) {
            maxScore = scores[i];
        }
        if (scores[i] < minScore) {
            minScore = scores[i];
        }
    }
    
    double average = sum / SIZE;
    
    // 统计及格人数
    int passCount = 0;
    for (int i = 0; i < SIZE; i++) {
        if (scores[i] >= 60) {
            passCount++;
        }
    }
    
    // 输出统计结果
    cout << "\n===== 成绩统计 =====" << endl;
    cout << "总分:" << sum << endl;
    cout << "平均分:" << average << endl;
    cout << "最高分:" << maxScore << endl;
    cout << "最低分:" << minScore << endl;
    cout << "及格人数:" << passCount << " / " << SIZE << endl;
    cout << "及格率:" << (passCount * 100.0 / SIZE) << "%" << endl;
    
    return 0;
}

案例2:冒泡排序

#include <iostream>
using namespace std;

int main() {
    int arr[] = {64, 34, 25, 12, 22, 11, 90};
    int n = 7;
    
    cout << "原数组:";
    for (int i = 0; i < n; i++) {
        cout << arr[i] << " ";
    }
    cout << endl;
    
    // 冒泡排序
    for (int i = 0; i < n - 1; i++) {
        for (int j = 0; j < n - 1 - i; j++) {
            if (arr[j] > arr[j + 1]) {
                // 交换
                int temp = arr[j];
                arr[j] = arr[j + 1];
                arr[j + 1] = temp;
            }
        }
    }
    
    cout << "排序后:";
    for (int i = 0; i < n; i++) {
        cout << arr[i] << " ";
    }
    cout << endl;
    
    return 0;
}

输出:

原数组:64 34 25 12 22 11 90
排序后:11 12 22 25 34 64 90

案例3:查找元素

#include <iostream>
using namespace std;

int main() {
    int numbers[] = {10, 25, 33, 47, 52, 68, 79, 85, 91};
    int n = 9;
    int target;
    bool found = false;
    int position = -1;
    
    cout << "数组中的元素:";
    for (int i = 0; i < n; i++) {
        cout << numbers[i] << " ";
    }
    cout << endl;
    
    cout << "请输入要查找的数字:";
    cin >> target;
    
    // 查找
    for (int i = 0; i < n; i++) {
        if (numbers[i] == target) {
            found = true;
            position = i;
            break;
        }
    }
    
    if (found) {
        cout << "找到了!位置在第 " << (position + 1) << " 个(下标 " << position << ")" << endl;
    } else {
        cout << "没找到该数字" << endl;
    }
    
    return 0;
}

案例4:字符串处理

#include <iostream>
#include <string>
using namespace std;

int main() {
    string text;
    
    cout << "请输入一句话:";
    getline(cin, text);
    
    // 统计字符
    int letters = 0;
    int digits = 0;
    int spaces = 0;
    int others = 0;
    
    for (int i = 0; i < text.length(); i++) {
        char ch = text[i];
        
        if ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z')) {
            letters++;
        } else if (ch >= '0' && ch <= '9') {
            digits++;
        } else if (ch == ' ') {
            spaces++;
        } else {
            others++;
        }
    }
    
    cout << "\n===== 统计结果 =====" << endl;
    cout << "总字符数:" << text.length() << endl;
    cout << "字母:" << letters << endl;
    cout << "数字:" << digits << endl;
    cout << "空格:" << spaces << endl;
    cout << "其他:" << others << endl;
    
    return 0;
}

案例5:简易通讯录

#include <iostream>
#include <string>
using namespace std;

int main() {
    const int MAX = 10;
    string names[MAX];
    string phones[MAX];
    int count = 0;
    int choice;
    
    do {
        cout << "\n===== 通讯录 =====" << endl;
        cout << "1. 添加联系人" << endl;
        cout << "2. 显示所有联系人" << endl;
        cout << "3. 查找联系人" << endl;
        cout << "4. 退出" << endl;
        cout << "请选择(1-4):";
        cin >> choice;
        cin.ignore();
        
        switch (choice) {
            case 1:
                if (count < MAX) {
                    cout << "请输入姓名:";
                    getline(cin, names[count]);
                    cout << "请输入电话:";
                    getline(cin, phones[count]);
                    count++;
                    cout << "添加成功!" << endl;
                } else {
                    cout << "通讯录已满!" << endl;
                }
                break;
                
            case 2:
                if (count == 0) {
                    cout << "通讯录为空!" << endl;
                } else {
                    cout << "\n===== 联系人列表 =====" << endl;
                    for (int i = 0; i < count; i++) {
                        cout << (i + 1) << ". " << names[i] << " - " << phones[i] << endl;
                    }
                }
                break;
                
            case 3: {
                string searchName;
                cout << "请输入要查找的姓名:";
                getline(cin, searchName);
                
                bool found = false;
                for (int i = 0; i < count; i++) {
                    if (names[i] == searchName) {
                        cout << "找到了:" << names[i] << " - " << phones[i] << endl;
                        found = true;
                        break;
                    }
                }
                
                if (!found) {
                    cout << "未找到该联系人!" << endl;
                }
                break;
            }
                
            case 4:
                cout << "再见!" << endl;
                break;
                
            default:
                cout << "无效选择!" << endl;
        }
    } while (choice != 4);
    
    return 0;
}

🎯 小结

这一章我们学习了数组和字符串:

概念说明
数组存储一组相同类型数据的集合
数组定义类型 数组名[大小];
数组初始化int arr[] = {1, 2, 3};
数组下标从0开始,arr[0] 表示第一个元素
C风格字符串字符数组,以 \0 结尾
string类C++字符串类,使用更方便
遍历数组使用 for 循环访问所有元素

重要提醒:

  • ⚠️ 数组下标从 0 开始
  • ⚠️ 不要越界访问数组
  • ⚠️ 字符串推荐使用 string 类

💪 练习题

动手练习巩固知识:

  1. 写一个程序,创建一个数组存储10个整数,然后计算所有偶数的和
  2. 写一个程序,输入5个数字,按从大到小的顺序输出
  3. 写一个程序,判断一个字符串是否是回文(如"level"、"noon")
  4. 写一个程序,统计一个字符串中某个字符出现的次数
  5. 写一个程序,实现数组的去重功能
点击查看参考答案

题目1 参考答案:

#include <iostream>
using namespace std;

int main() {
    int arr[10];
    int evenSum = 0;
    
    cout << "请输入10个整数:" << endl;
    for (int i = 0; i < 10; i++) {
        cout << "第" << (i + 1) << "个:";
        cin >> arr[i];
        
        if (arr[i] % 2 == 0) {
            evenSum += arr[i];
        }
    }
    
    cout << "所有偶数的和:" << evenSum << endl;
    
    return 0;
}

题目3 参考答案:

#include <iostream>
#include <string>
using namespace std;

int main() {
    string str;
    cout << "请输入一个字符串:";
    cin >> str;
    
    bool isPalindrome = true;
    int len = str.length();
    
    for (int i = 0; i < len / 2; i++) {
        if (str[i] != str[len - 1 - i]) {
            isPalindrome = false;
            break;
        }
    }
    
    if (isPalindrome) {
        cout << str << " 是回文" << endl;
    } else {
        cout << str << " 不是回文" << endl;
    }
    
    return 0;
}

🎉 恭喜你!

你已经完成了 C++ 基础教程的所有章节!

你学到了什么?

✅ 环境搭建和第一个程序
✅ 变量和数据类型
✅ 输入输出和运算符
✅ 条件判断(if/else/switch)
✅ 循环语句(for/while/do-while)
✅ 函数基础
✅ 数组和字符串

下一步学什么?

现在你已经掌握了 C++ 的基础知识,可以继续学习:

  • 指针和引用 - C++ 的核心特性
  • 面向对象编程 - 类、对象、继承、多态
  • STL 标准模板库 - vector、map、set 等容器
  • 文件操作 - 读写文件
  • 异常处理 - try-catch

💡 学习建议

  1. 多写代码 - 编程是实践性技能,多动手才能进步
  2. 做项目 - 用所学知识做一些小项目(计算器、学生管理系统等)
  3. 阅读代码 - 看看别人是怎么写的
  4. 持续学习 - 编程技术日新月异,要保持学习

感谢你的学习!祝你在编程的道路上越走越远!
更多编程教程,请访问 编程指南

最近更新: 2025/12/26 17:25
Contributors: 王长安
Prev
第6章 - 函数基础