如何在C ++中拆分字符串向量?
从文件中读取输入字符串值,其格式如下所示。
P00 ARRIVAL:3 CPU:1 I/O:3 CPU:7 I/O:1 CPU:3
P01 ARRIVAL:2 CPU:9
P02 ARRIVAL:0 CPU:6
P03 ARRIVAL:4 CPU:1
P04 ARRIVAL:0 CPU:5
但是,我只需要像
那样的值p00 3 1 3 7 1 3
p01 2 9
p02 0 6
...
这是我的代码部分。该文件逐行读取,每行保存在字符串向量数组中。
vector<string> procList; // file
void readProc(char *filename) {
std::ifstream file(filename);
std::string str;
while (std::getline(file, str))
{
procList.push_back(str);
}
file.close();
for (int i = 0, size = procList.size(); i < size; ++i) {
_tprintf(TEXT("[%s] \n"), procList[i]);
}
}
感谢。
答案 0 :(得分:0)
使用regexps进行解析:
#include <regex>
std::vector<std::string> example = {
"P00 ARRIVAL:3 CPU:1 I/O:3 CPU:7 I/O:1 CPU:3",
"P01 ARRIVAL:2 CPU:9",
"P02 ARRIVAL:0 CPU:6",
"P03 ARRIVAL:4 CPU:1",
"P04 ARRIVAL:0 CPU:5"
};
std::regex re{"[\\w\\d]+:(\\d+)"};
for (auto s : example) {
std::cout << "\n";
std::regex_token_iterator<std::string::iterator> it{s.begin(), s.end(), re, 1};
decltype(it) end{};
while (it != end) std::cout << *it++ << ":";
}
将输出:
3:1:3:7:1:3:
2:9:
0:6:
4:1:
0:5:
使用regex_token_iterator,您还可以指定迭代数据中的名称和值。您在regexp中指定了两个组(使用括号),然后在构造函数中指定regex_token_iterator在迭代期间使用以下内容组合(子匹配):{1,2}。
std::regex re{R"(([\w\d/]+):(\d+))"};
for (auto s : example) {
std::cout << "\n";
using reg_itr = std::regex_token_iterator<std::string::iterator>;
for (reg_itr it{s.begin(), s.end(), re, {1,2}}, end{}; it != end;) {
std::cout << *it++ << ":"; std::cout << std::stoi(*it++) << " ";
}
}
将输出:
ARRIVAL:3 CPU:1 I/O:3 CPU:7 I/O:1 CPU:3
ARRIVAL:2 CPU:9
ARRIVAL:0 CPU:6
ARRIVAL:4 CPU:1
ARRIVAL:0 CPU:5
答案 1 :(得分:0)
假设格式为id {key:value}
。以下代码使用stringstream
和getline
。可能有问题,我还没有测试过。
vector<string> procList; // file
void readProc(char *filename) {
std::ifstream file(filename);
std::string str;
while (std::getline(file, str))
{
std::stringstream in(str);
std::stringstream out;
std::string temp;
in>>temp;
out<<temp;
while(getline(in, temp, ':')) {
in>>temp;
out<<"\t"<<temp;
}
procList.push_back(out.str());
}
file.close();
for (int i = 0, size = procList.size(); i < size; ++i) {
_tprintf(TEXT("[%s] \n"), procList[i]);
}
}