C++数组与字符串:数据存储与操作的核心

一、学习目标与重点
本章将深入探讨C++中的数组与字符串,它们是数据存储与操作的核心。通过学习,你将能够:
二、数组的基本概念与使用
2.1 数组的定义与初始化
数组是一种连续内存空间的数据结构,用于存储相同类型的元素。
#include <iostream>
int main() {
std::cout << "=== 数组的基本概念与使用示例 ===" << std::endl;
// 声明数组
int numbers[5];
// 初始化数组
numbers[0] = 10;
numbers[1] = 20;
numbers[2] = 30;
numbers[3] = 40;
numbers[4] = 50;
// 访问数组元素
std::cout << "数组元素: ";
for (int i = 0; i < 5; i++) {
std::cout << numbers[i] << " ";
}
std::cout << std::endl;
// 初始化数组的其他方式
int scores[] = {85, 90, 95, 88, 92};
std::cout << "scores数组: ";
for (int i = 0; i < 5; i++) {
std::cout << scores[i] << " ";
}
std::cout << std::endl;
int matrix[3][2] = {
{1, 2},
{3, 4},
{5, 6}
};
std::cout << "matrix数组: " << std::endl;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 2; j++) {
std::cout << matrix[i][j] << " ";
}
std::cout << std::endl;
}
return 0;
}
2.2 数组的访问与操作
#include <iostream>
#include <algorithm> // 用于std::sort
int main() {
std::cout << "=== 数组的访问与操作示例 ===" << std::endl;
int numbers[] = {10, 20, 30, 40, 50};
int size = sizeof(numbers) / sizeof(numbers[0]);
// 访问数组元素
std::cout << "第一个元素: " << numbers[0] << std::endl;
std::cout << "最后一个元素: " << numbers[size – 1] << std::endl;
// 计算数组的和
int sum = 0;
for (int i = 0; i < size; i++) {
sum += numbers[i];
}
std::cout << "数组的和: " << sum << std::endl;
// 计算数组的平均值
double average = static_cast<double>(sum) / size;
std::cout << "数组的平均值: " << average << std::endl;
// 查找数组中的最大值和最小值
int max = numbers[0];
int min = numbers[0];
for (int i = 1; i < size; i++) {
if (numbers[i] > max) {
max = numbers[i];
}
if (numbers[i] < min) {
min = numbers[i];
}
}
std::cout << "数组的最大值: " << max << std::endl;
std::cout << "数组的最小值: " << min << std::endl;
// 排序数组
std::sort(numbers, numbers + size);
std::cout << "排序后的数组: ";
for (int i = 0; i < size; i++) {
std::cout << numbers[i] << " ";
}
std::cout << std::endl;
return 0;
}
三、多维数组
3.1 二维数组
#include <iostream>
int main() {
std::cout << "=== 二维数组示例 ===" << std::endl;
// 定义并初始化二维数组
int matrix[3][3] = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
// 访问二维数组元素
std::cout << "二维数组: " << std::endl;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
std::cout << matrix[i][j] << " ";
}
std::cout << std::endl;
}
// 计算二维数组的和
int sum = 0;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
sum += matrix[i][j];
}
}
std::cout << "二维数组的和: " << sum << std::endl;
// 计算二维数组的行和列和
std::cout << "行和: ";
for (int i = 0; i < 3; i++) {
int rowSum = 0;
for (int j = 0; j < 3; j++) {
rowSum += matrix[i][j];
}
std::cout << rowSum << " ";
}
std::cout << std::endl;
std::cout << "列和: ";
for (int j = 0; j < 3; j++) {
int colSum = 0;
for (int i = 0; i < 3; i++) {
colSum += matrix[i][j];
}
std::cout << colSum << " ";
}
std::cout << std::endl;
return 0;
}
3.2 三维数组
#include <iostream>
int main() {
std::cout << "=== 三维数组示例 ===" << std::endl;
// 定义并初始化三维数组
int cube[2][3][4] = {
{
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12}
},
{
{13, 14, 15, 16},
{17, 18, 19, 20},
{21, 22, 23, 24}
}
};
// 访问三维数组元素
std::cout << "三维数组: " << std::endl;
for (int i = 0; i < 2; i++) {
std::cout << "第" << i + 1 << "层: " << std::endl;
for (int j = 0; j < 3; j++) {
for (int k = 0; k < 4; k++) {
std::cout << cube[i][j][k] << " ";
}
std::cout << std::endl;
}
std::cout << std::endl;
}
// 计算三维数组的和
int sum = 0;
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 3; j++) {
for (int k = 0; k < 4; k++) {
sum += cube[i][j][k];
}
}
}
std::cout << "三维数组的和: " << sum << std::endl;
return 0;
}
四、C风格字符串
4.1 C风格字符串的定义与初始化
C风格字符串是一个以null字符(‘\\0’)结尾的字符数组。
#include <iostream>
#include <cstring> // 用于字符串操作函数
int main() {
std::cout << "=== C风格字符串示例 ===" << std::endl;
// 定义并初始化C风格字符串
char str1[] = "Hello";
char str2[6] = {'H', 'e', 'l', 'l', 'o', '\\0'};
// 访问C风格字符串
std::cout << "str1: " << str1 << std::endl;
std::cout << "str2: " << str2 << std::endl;
// 字符串长度
std::cout << "str1的长度: " << strlen(str1) << std::endl;
std::cout << "str2的长度: " << strlen(str2) << std::endl;
// 字符串比较
char str3[] = "World";
int compareResult = strcmp(str1, str3);
if (compareResult < 0) {
std::cout << str1 << " < " << str3 << std::endl;
} else if (compareResult > 0) {
std::cout << str1 << " > " << str3 << std::endl;
} else {
std::cout << str1 << " == " << str3 << std::endl;
}
// 字符串复制
char str4[20];
strcpy(str4, str1);
std::cout << "str4: " << str4 << std::endl;
// 字符串连接
char str5[20] = "Hello";
strcat(str5, " World");
std::cout << "str5: " << str5 << std::endl;
return 0;
}
4.2 C风格字符串的注意事项
#include <iostream>
#include <cstring>
int main() {
std::cout << "=== C风格字符串注意事项示例 ===" << std::endl;
// 字符串缓冲区溢出
char str1[5] = "Hello"; // 数组大小为5,字符串长度为5,但没有null字符的空间
std::cout << "str1: " << str1 << std::endl;
// 使用strncpy防止缓冲区溢出
char str2[5];
strncpy(str2, "Hello", 4);
str2[4] = '\\0';
std::cout << "str2: " << str2 << std::endl;
// 字符串比较时避免使用==运算符
char str3[] = "Hello";
char str4[] = "Hello";
if (strcmp(str3, str4) == 0) {
std::cout << str3 << " == " << str4 << std::endl;
}
return 0;
}
五、C++字符串类
5.1 string类的定义与初始化
C++标准库提供了string类,简化了字符串操作。
#include <iostream>
#include <string>
int main() {
std::cout << "=== C++字符串类示例 ===" << std::endl;
// 定义并初始化string对象
std::string str1 = "Hello";
std::string str2("World");
std::string str3;
// 访问string对象
std::cout << "str1: " << str1 << std::endl;
std::cout << "str2: " << str2 << std::endl;
std::cout << "str3: " << str3 << std::endl;
// 字符串长度
std::cout << "str1的长度: " << str1.length() << std::endl;
std::cout << "str2的长度: " << str2.size() << std::endl;
// 字符串比较
int compareResult = str1.compare(str2);
if (compareResult < 0) {
std::cout << str1 << " < " << str2 << std::endl;
} else if (compareResult > 0) {
std::cout << str1 << " > " << str2 << std::endl;
} else {
std::cout << str1 << " == " << str2 << std::endl;
}
// 字符串复制
std::string str4 = str1;
std::cout << "str4: " << str4 << std::endl;
// 字符串连接
std::string str5 = str1 + " " + str2;
std::cout << "str5: " << str5 << std::endl;
return 0;
}
5.2 string类的常用操作
#include <iostream>
#include <string>
int main() {
std::cout << "=== C++字符串类常用操作示例 ===" << std::endl;
std::string str = "Hello, World!";
// 访问单个字符
std::cout << "第一个字符: " << str[0] << std::endl;
std::cout << "第二个字符: " << str.at(1) << std::endl;
// 修改单个字符
str[7] = 'W';
std::cout << "修改后的字符串: " << str << std::endl;
// 查找子字符串
size_t pos = str.find("World");
if (pos != std::string::npos) {
std::cout << "找到了World,位置: " << pos << std::endl;
}
// 替换子字符串
str.replace(pos, 5, "C++");
std::cout << "替换后的字符串: " << str << std::endl;
// 提取子字符串
std::string subStr = str.substr(7, 3);
std::cout << "提取的子字符串: " << subStr << std::endl;
// 插入子字符串
str.insert(5, " Beautiful");
std::cout << "插入后的字符串: " << str << std::endl;
// 删除子字符串
str.erase(5, 10);
std::cout << "删除后的字符串: " << str << std::endl;
// 转换为大写
std::string upperStr = str;
for (char& c : upperStr) {
c = toupper(c);
}
std::cout << "大写字符串: " << upperStr << std::endl;
// 转换为小写
std::string lowerStr = str;
for (char& c : lowerStr) {
c = tolower(c);
}
std::cout << "小写字符串: " << lowerStr << std::endl;
// 清空字符串
str.clear();
std::cout << "清空后的字符串: " << str << std::endl;
return 0;
}
六、综合案例:实现一个简单的文本处理工具
6.1 项目结构
TextProcessingTool/
├── include/
│ └── TextProcessor.h
├── src/
│ ├── TextProcessor.cpp
│ └── main.cpp
└── build/
6.2 核心代码
// include/TextProcessor.h
#ifndef TEXTPROCESSOR_H
#define TEXTPROCESSOR_H
#include <string>
#include <vector>
class TextProcessor {
public:
// 计算单词个数
static int countWords(const std::string& text);
// 计算字符个数
static int countCharacters(const std::string& text);
// 计算行数
static int countLines(const std::string& text);
// 统计单词频率
static std::vector<std::pair<std::string, int>> countWordFrequency(const std::string& text);
// 查找子字符串
static int findSubstring(const std::string& text, const std::string& substr);
// 替换子字符串
static std::string replaceSubstring(const std::string& text, const std::string& oldStr, const std::string& newStr);
// 分割字符串
static std::vector<std::string> split(const std::string& text, char delimiter);
// 去除字符串首尾的空格
static std::string trim(const std::string& text);
};
#endif // TEXTPROCESSOR_H
// src/TextProcessor.cpp
#include "TextProcessor.h"
#include <algorithm>
#include <cctype>
#include <map>
int TextProcessor::countWords(const std::string& text) {
int count = 0;
bool inWord = false;
for (char c : text) {
if (std::isspace(c)) {
inWord = false;
} else if (!inWord) {
inWord = true;
count++;
}
}
return count;
}
int TextProcessor::countCharacters(const std::string& text) {
return text.size();
}
int TextProcessor::countLines(const std::string& text) {
int count = 0;
for (char c : text) {
if (c == '\\n') {
count++;
}
}
return count;
}
std::vector<std::pair<std::string, int>> TextProcessor::countWordFrequency(const std::string& text) {
std::map<std::string, int> wordCount;
std::string currentWord;
for (char c : text) {
if (std::isalpha(c)) {
currentWord += std::tolower(c);
} else if (!currentWord.empty()) {
wordCount[currentWord]++;
currentWord.clear();
}
}
if (!currentWord.empty()) {
wordCount[currentWord]++;
}
std::vector<std::pair<std::string, int>> frequencyList(wordCount.begin(), wordCount.end());
std::sort(frequencyList.begin(), frequencyList.end(),
[](const std::pair<std::string, int>& a, const std::pair<std::string, int>& b) {
return a.second > b.second;
});
return frequencyList;
}
int TextProcessor::findSubstring(const std::string& text, const std::string& substr) {
size_t pos = text.find(substr);
return (pos != std::string::npos) ? static_cast<int>(pos) : –1;
}
std::string TextProcessor::replaceSubstring(const std::string& text, const std::string& oldStr, const std::string& newStr) {
std::string result = text;
size_t pos = 0;
while ((pos = result.find(oldStr, pos)) != std::string::npos) {
result.replace(pos, oldStr.length(), newStr);
pos += newStr.length();
}
return result;
}
std::vector<std::string> TextProcessor::split(const std::string& text, char delimiter) {
std::vector<std::string> tokens;
std::string currentToken;
for (char c : text) {
if (c == delimiter) {
if (!currentToken.empty()) {
tokens.push_back(currentToken);
currentToken.clear();
}
} else {
currentToken += c;
}
}
if (!currentToken.empty()) {
tokens.push_back(currentToken);
}
return tokens;
}
std::string TextProcessor::trim(const std::string& text) {
size_t start = 0;
size_t end = text.size() – 1;
while (start < text.size() && std::isspace(text[start])) {
start++;
}
while (end > start && std::isspace(text[end])) {
end—;
}
return text.substr(start, end – start + 1);
}
// src/main.cpp
#include <iostream>
#include <string>
#include <fstream>
#include "TextProcessor.h"
int main() {
std::cout << "=== 文本处理工具 ===" << std::endl;
// 读取文件内容
std::ifstream file("sample.txt");
if (!file.is_open()) {
std::cerr << "无法打开文件" << std::endl;
return 1;
}
std::string text;
std::string line;
while (std::getline(file, line)) {
text += line + "\\n";
}
file.close();
// 显示文件内容
std::cout << "文件内容: " << std::endl;
std::cout << text << std::endl;
// 文本统计
std::cout << "\\n文本统计: " << std::endl;
std::cout << "字符数: " << TextProcessor::countCharacters(text) << std::endl;
std::cout << "单词数: " << TextProcessor::countWords(text) << std::endl;
std::cout << "行数: " << TextProcessor::countLines(text) << std::endl;
// 单词频率统计
std::cout << "\\n单词频率统计: " << std::endl;
std::vector<std::pair<std::string, int>> frequencyList = TextProcessor::countWordFrequency(text);
for (const auto& pair : frequencyList) {
std::cout << pair.first << ": " << pair.second << std::endl;
}
// 查找和替换
std::string searchStr = "C++";
int position = TextProcessor::findSubstring(text, searchStr);
if (position != –1) {
std::cout << "\\n找到了\\"" << searchStr << "\\",位置: " << position << std::endl;
std::string replacedText = TextProcessor::replaceSubstring(text, searchStr, "C Plus Plus");
std::cout << "替换后的文本: " << std::endl;
std::cout << replacedText << std::endl;
} else {
std::cout << "\\n未找到\\"" << searchStr << "\\"" << std::endl;
}
// 分割字符串
std::cout << "\\n按空格分割字符串: " << std::endl;
std::vector<std::string> tokens = TextProcessor::split(text, ' ');
for (const std::string& token : tokens) {
std::cout << "\\"" << token << "\\"" << std::endl;
}
// 修剪字符串
std::string untrimmedStr = " Hello, World! ";
std::string trimmedStr = TextProcessor::trim(untrimmedStr);
std::cout << "\\n未修剪的字符串: \\"" << untrimmedStr << "\\"" << std::endl;
std::cout << "修剪后的字符串: \\"" << trimmedStr << "\\"" << std::endl;
return 0;
}
6.3 项目构建与运行
# 创建构建目录
mkdir -p build && cd build
# 配置CMake
cmake -DCMAKE_BUILD_TYPE=Release ..
# 编译项目
cmake –build . –config Release
# 运行程序
./TextProcessingTool
七、总结与练习
7.1 本章总结
本章介绍了C++数组与字符串的核心概念和使用方法,包括:


![【题解】[COCI 2025/2026 #6] 滑雪 / Skijanje(李超树 0 基础友好喵)-171主机测评](https://www.171host.com/wp-content/uploads/2026/08/20260826083930-6a8ea642697bc-220x25.png)

