C++如何将包含多组数据的字符串拆分存入不同vector中
实现方案
针对你提到的按字段拆分vector的需求,这里提供两种常用实现方式,默认你使用的是C++语言(涉及vector容器操作):
方案1:字符串流拆分(更推荐,性能更高)
你的字段都是空白符分隔,没有嵌套空格的场景,用istringstream拆分比正则更简单高效:
#include <vector> #include <string> #include <sstream> int main() { // 假设raw_lines是你存储所有原始行的输入vector std::vector<std::string> raw_lines = { "A240 001 KERUL 41.857778 52.139167", "A240 002 TABAB 40.903333 52.608333", // 其余原始数据 }; // 定义存储五个字段的vector,后两个字段可按需选择存string或double std::vector<std::string> col1, col2, col3; std::vector<double> col4, col5; for (const auto& line : raw_lines) { std::istringstream iss(line); std::string f1, f2, f3; double f4 = 0, f5 = 0; // 自动按任意空白符拆分,同时校验每行格式是否合法 if (iss >> f1 >> f2 >> f3 >> f4 >> f5) { col1.push_back(f1); col2.push_back(f2); col3.push_back(f3); col4.push_back(f4); col5.push_back(f5); } } return 0; }
方案2:正则实现(适合需要强格式校验的场景)
如果你需要同时校验字段格式(比如第二个字段必须是3位数字),可以用正则实现:
#include <vector> #include <string> #include <regex> int main() { std::vector<std::string> raw_lines = { /* 原始数据 */ }; std::vector<std::string> col1, col2, col3; std::vector<double> col4, col5; // 正则规则:\S+匹配非空白的字段,\s+匹配分隔的任意空白符 std::regex re(R"((\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(\S+))"); std::smatch match; for (const auto& line : raw_lines) { if (std::regex_match(line, match, re)) { col1.push_back(match[1].str()); col2.push_back(match[2].str()); col3.push_back(match[3].str()); col4.push_back(std::stod(match[4].str())); col5.push_back(std::stod(match[5].str())); } } return 0; }
两种方案都兼容字段间的空格、制表符分隔,也会自动跳过行首尾的空白字符。
内容的提问来源于stack exchange,提问作者NikoD
相关产品推荐
相关产品推荐

