字符串数组的基本概念
在C++中,字符串数组通常指存储多个字符串的数组。字符串本身可以用C风格字符数组(char[]
)或C++的std::string
类表示,因此字符串数组也有两种常见形式:
- C风格字符串数组:数组元素为
char[]
或char*
。 - C++风格字符串数组:数组元素为
std::string
。
C风格字符串数组
C风格字符串数组是字符指针数组,每个元素指向一个以\0
结尾的字符数组。
声明与初始化
const char* colors[] = {"Red", "Green", "Blue"}; // 字符指针数组
char fruits[][10] = {"Apple", "Banana", "Cherry"}; // 二维字符数组
遍历示例
for (int i = 0; i < 3; i++) {
std::cout << colors[i] << std::endl;
}
注意事项
- 需手动管理内存。
- 使用
strcpy
等函数操作字符串。
C++风格字符串数组
使用std::string
数组更安全,无需关心内存管理和字符串长度。
声明与初始化
#include <string>
std::string names[] = {"Alice", "Bob", "Charlie"};
遍历示例
for (const auto& name : names) {
std::cout << name << std::endl;
}
动态数组(推荐)
使用std::vector<std::string>
更灵活:
#include <vector>
#include <string>
std::vector<std::string> cities = {"New York", "Tokyo", "London"};
动态分配字符串数组
使用new
分配
std::string* dynamicArray = new std::string[3];
dynamicArray[0] = "C++";
dynamicArray[1] = "Java";
// 释放内存
delete[] dynamicArray;
使用std::vector
std::vector<std::string> dynamicVec;
dynamicVec.push_back("Python");
dynamicVec.push_back("JavaScript");
多维字符串数组
二维数组示例
std::string matrix[2][2] = {{"A1", "A2"}, {"B1", "B2"}};
使用嵌套容器
std::vector<std::vector<std::string>> table = {
{"X", "Y"}, {"Z", "W"}
};
常见操作
排序字符串数组
#include <algorithm>
std::sort(std::begin(names), std::end(names));
查找字符串
auto it = std::find(std::begin(names), std::end(names), "Bob");
if (it != std::end(names)) {
std::cout << "Found" << std::endl;
}
性能与建议
- 优先选择
std::vector<std::string>
:避免手动内存管理,支持动态扩容。 - 避免原始指针:除非需要兼容C代码或特定性能优化。
- 使用范围循环:简化遍历代码(C++11及以上)。