我有一个字符串向量。
Vector <string> myVector;
假设myVector当前有2个字符串。
myVector[0] is "id1|Name1|Age1"
myVector[1] is "id2|Name2|Age2"
现在我想基于分隔符“|”拆分向量中的每个字符串 并将结果存储在id,name和age的结构中。
任何人都可以帮忙吗?
答案 0 :(得分:0)
类似的东西,你需要检查它
struct{
unsigned int id;
std::string name;
unsigned int age;
}MyStruct;
int main()
{
std::string line;
std::vector<std::string> myVector = {"id1|Name1|Age1","id2|Name2|Age2"};
std::vector<MyStruct> myStruct;
for (string::const_iterator it = myVector .begin(); it != myVector.end(); it++)
{
vector<std::string> splitLine;
while(std::getline(*it,line,'|'))
splitLine.push_back(line);
if (splitLine.size()> 0)
{
MyStruct mSt;
mSt.id = (int)splitLine[0];
mSt.name = splitLine[1];
mSt.age= (int)splitLine[2];
myStruct.push_back(mSt);
}
}
return 0;
}
答案 1 :(得分:0)
使用substr()和find()很简单。
#include <iostream>
#include <vector>
#include <string>
using namespace std;
struct Person
{
string m_id;
string m_name;
int m_age;
};
int main()
{
vector<string> data;
vector<Person> people;
data.push_back("id1|Name1|25");
data.push_back("id2|Name2|35");
for(int i(0); i < data.size(); ++i){
size_t idx = data[i].find("|");
string id = data[i].substr( 0, idx);
string name = data[i].substr(idx+1, data[i].find_first_of("|", idx) + idx - 1);
string age = data[i].substr( data[i].find_last_of("|") + 1 );
Person p = {id, name, stoi(age)};
people.push_back(p);
}
for(int i(0); i < people.size(); ++i)
cout << people[i].m_id << " " << people[i].m_name << " " << people[i].m_age << endl;
return 0;
}
,输出
id1 Name1 25
id2 Name2 35