首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計疑難解答

C++ 字符串解析轉二維數組:自定義分隔符 <255> <000> 實戰代碼詳解

     編輯:程式設計疑難解答

問題描述

輸入字符串:id<255>name<000>1<255>科技<000>7<255>河南

其中 <255> 為列分隔符,<000> 為行分隔符。需轉換為二維數組結構:[[id,name],[1,科技],[7,河南]]。

核心邏輯

  1. 按行分隔符 <000> 分割得到行數組。
  2. 每行按列分隔符 <255> 分割得到字段。
  3. 組裝為目標格式字符串或結構體/容器。

完整 C++ 實現(標準庫,無 MFC 依賴)

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

using namespace std;

// 通用分割函數:按子串分割
vector<string> split(const string& str, const string& delim) {
    vector<string> tokens;
    size_t start = 0, end = 0;
    while ((end = str.find(delim, start)) != string::npos) {
        tokens.push_back(str.substr(start, end - start));
        start = end + delim.length();
    }
    tokens.push_back(str.substr(start));
    return tokens;
}

int main() {
    string input = "id<255>name<000>1<255>科技<000>7<255>河南";
    const string ROW_DELIM = "<000>";
    const string COL_DELIM = "<255>";

    // 1. 分行
    vector<string> rows = split(input, ROW_DELIM);
    
    // 2. 每行分列,構建二維向量
    vector<vector<string>> matrix;
    for (const auto& row : rows) {
        if (!row.empty()) {
            matrix.push_back(split(row, COL_DELIM));
        }
    }

    // 3. 輸出驗證
    cout << "[";
    for (size_t i = 0; i < matrix.size(); ++i) {
        cout << "[";
        for (size_t j = 0; j < matrix[i].size(); ++j) {
            cout << matrix[i][j];
            if (j + 1 < matrix[i].size()) cout << ",";
        }
        cout << "]";
        if (i + 1 < matrix.size()) cout << ",";
    }
    cout << "]" << endl;
    // 輸出: [[id,name],[1,科技],[7,河南]]

    return 0;
}

關鍵點解析

  • 多字符分隔符:使用 string::find 而非 strtok(僅支持單字符)。
  • 邊界處理:末尾無分隔符、空行、連續分隔符均正確處理。
  • 編碼兼容:源文件保存為 UTF-8,中文「科技」「河南」作為普通字節序列處理,無需特殊邏輯。
  • 擴展性:split 函數可復用於 CSV、日誌解析等場景。

進階:直接生成目標格式字符串

string toTargetFormat(const vector<vector<string>>& mat) {
    ostringstream oss;
    oss << "[";
    for (size_t i = 0; i < mat.size(); ++i) {
        oss << "[";
        for (size_t j = 0; j < mat[i].size(); ++j) {
            oss << mat[i][j];
            if (j + 1 < mat[i].size()) oss << ",";
        }
        oss << "]";
        if (i + 1 < mat.size()) oss << ",";
    }
    oss << "]";
    return oss.str();
}

總結

針對自定義多字符分隔符的字符串轉二維結構,**通用分割函數 + 二維向量** 是最清晰、可維護的 C++ 實現。避免手動指針操作,利用標準庫 string::find、substr、vector 實現健壯解析。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved