You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++如何将数组的字符串元素拆分为单个字符组成的子数组

C++ 字符串数组拆分转二维字符数组实现

实现思路

  • 遍历原字符串数组的每一个字符串元素
  • 对单个字符串遍历其每个字符,将字符依次存入对应的子数组中
  • 所有子数组汇总后得到目标二维数组

代码示例

这里以STL容器实现为例,兼容C++11及以上标准:

#include <iostream>
#include <vector>
#include <string>

int main() {
    // 原数组
    std::vector<std::string> array_1 = {"first", "second", "third"};
    // 定义目标二维数组
    std::vector<std::vector<char>> array_2;

    // 遍历原数组每个字符串
    for (const std::string& str : array_1) {
        std::vector<char> char_list;
        // 拆分字符串为单个字符存入子数组
        for (char c : str) {
            char_list.push_back(c);
        }
        array_2.push_back(char_list);
    }

    // 测试输出验证结果
    for (const auto& sub_arr : array_2) {
        std::cout << "[";
        for (size_t i = 0; i < sub_arr.size(); ++i) {
            if (i > 0) std::cout << ",";
            std::cout << sub_arr[i];
        }
        std::cout << "]" << std::endl;
    }

    return 0;
}

运行输出结果

[f,i,r,s,t]
[s,e,c,o,n,d]
[t,h,i,r,d]

补充说明

  • 如果你的原数组是C风格的char*数组,只需要修改遍历逻辑适配C风格字符串即可,核心拆分逻辑不变
  • 如果需要固定大小的数组而非动态容器,可以提前计算每个字符串长度后分配对应大小的二维数组实现

内容的提问来源于stack exchange,提问作者FadedCoder

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.20 21:36:05