第6课: 数组与字符串
一维数组
#include <iostream>
using namespace std;
int main() {
// 声明并初始化数组
int numbers[5] = {10, 20, 30, 40, 50};
// 访问数组元素
cout << "第一个元素:" << numbers[0] << endl;
cout << "第三个元素:" << numbers[2] << endl;
// 修改数组元素
numbers[1] = 25;
// 遍历数组
for (int i = 0; i < 5; i++) {
cout << numbers[i] << " ";
}
cout << endl;
// 计算数组大小
int size = sizeof(numbers) / sizeof(numbers[0]);
cout << "数组大小:" << size << endl;
return 0;
}
多维数组
#include <iostream>
using namespace std;
int main() {
// 二维数组
int matrix[3][4] = {
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12}
};
// 访问元素
cout << "第2行第3列:" << matrix[1][2] << endl;
// 遍历二维数组
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 4; j++) {
cout << matrix[i][j] << "\t";
}
cout << endl;
}
return 0;
}
数组作为函数参数
#include <iostream>
using namespace std;
// 数组作为参数传递
void printArray(int arr[], int size) {
for (int i = 0; i < size; i++) {
cout << arr[i] << " ";
}
cout << endl;
}
// 计算数组总和
int sumArray(int arr[], int size) {
int sum = 0;
for (int i = 0; i < size; i++) {
sum += arr[i];
}
return sum;
}
int main() {
int numbers[] = {1, 2, 3, 4, 5};
int size = sizeof(numbers) / sizeof(numbers[0]);
printArray(numbers, size);
cout << "总和:" << sumArray(numbers, size) << endl;
return 0;
}
C风格字符串
#include <iostream>
#include <cstring> // C字符串函数库
using namespace std;
int main() {
// 字符数组
char str1[20] = "Hello";
char str2[] = "World";
// 字符串长度
cout << "str1长度:" << strlen(str1) << endl;
// 字符串拷贝
char str3[20];
strcpy(str3, str1);
cout << "拷贝结果:" << str3 << endl;
// 字符串连接
strcat(str1, " ");
strcat(str1, str2);
cout << "连接结果:" << str1 << endl;
// 字符串比较
if (strcmp(str1, str2) == 0) {
cout << "字符串相等" << endl;
} else {
cout << "字符串不相等" << endl;
}
return 0;
}
C++ string类
#include <iostream>
#include <string>
using namespace std;
int main() {
// 创建字符串
string str1 = "Hello";
string str2 = "World";
// 字符串连接
string str3 = str1 + " " + str2;
cout << str3 << endl;
// 字符串长度
cout << "长度:" << str3.length() << endl;
// 访问字符
cout << "第一个字符:" << str3[0] << endl;
// 子字符串
string sub = str3.substr(0, 5); // 从位置0开始,长度5
cout << "子串:" << sub << endl;
// 查找
size_t pos = str3.find("World");
if (pos != string::npos) {
cout << "找到World,位置:" << pos << endl;
}
// 替换
str3.replace(0, 5, "Hi");
cout << "替换后:" << str3 << endl;
// 插入
str3.insert(2, "!!!");
cout << "插入后:" << str3 << endl;
// 删除
str3.erase(2, 3);
cout << "删除后:" << str3 << endl;
return 0;
}
字符串输入
#include <iostream>
#include <string>
using namespace std;
int main() {
string name;
// cin只能读取到空格前
cout << "输入名字:";
cin >> name;
cout << "你好," << name << endl;
// getline可以读取整行
cin.ignore(); // 清除缓冲区
cout << "输入完整姓名:";
getline(cin, name);
cout << "你好," << name << endl;
return 0;
}
练习题
- 编写程序找出数组中的最大值和最小值
- 实现冒泡排序算法对数组排序
- 编写程序反转字符串
- 统计字符串中每个字符出现的次数
- 实现矩阵转置