字符串数组c++教程

字符串数组的基本概念

在C++中,字符串数组通常指存储多个字符串的数组。字符串本身可以用C风格字符数组(char[])或C++的std::string类表示,因此字符串数组也有两种常见形式:

  1. C风格字符串数组:数组元素为char[]char*
  2. 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及以上)。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值