輸入字符串:id<255>name<000>1<255>科技<000>7<255>河南
其中 <255> 為列分隔符,<000> 為行分隔符。需轉換為二維數組結構:[[id,name],[1,科技],[7,河南]]。
<000> 分割得到行數組。<255> 分割得到字段。#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(僅支持單字符)。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 實現健壯解析。