[英]split a string using multiple delimiters (including delimiters) in c++
[英]C++ reading string using more delimiters
我对 c++ 很陌生。 我的问题是我有一个可以是任意长度并以 \n 结尾的字符串。 例如:
const string s = "Daniel,20;Michael,99\n"
(始终是 "name,age;name,age;name,age.......\n")
我想将姓名和年龄分开并将其放入两个向量中以便可以存储。 但我不知道如何使用更多分隔符来管理字符串。 所以这个例子会像这样分开:
向量名称包含 {Daniel,Michael}
向量年龄包含 {20,99}
您可以为此目的使用stringstream
和getline
,但由于您有一个非常特定的格式,简单的std::string::find
可能会解决您的问题。 这是一个简单的例子:
#include <vector>
#include <string>
#include <cstdio>
#include <cstdlib>
#include <cstddef>
int main() {
std::string const s = "Daniel,20;Michael,99;Terry,42;Jack,34";
std::vector<std::string> names;
std::vector<int> ages;
std::size_t beg = 0;
std::size_t end = 0;
while ((end = s.find(',', end)) != s.npos) {
names.emplace_back(s, beg, end - beg);
char* pend;
ages.push_back(std::strtol(s.c_str() + end + 1, &pend, 10));
end = beg = pend - s.c_str() + 1;
}
for (auto&& n : names) std::puts(n.c_str());
for (auto&& a : ages) std::printf("%d\n", a);
}
抱歉,我的 C++ 技能已经褪色,但这是我会做的:-
vector <string> names;
vector <string> ages;
string inputString = "Daniel,20;Michael,99;Terry,42;Jack,34";
string word = "";
for(int i = 0; i<inputString.length(); i++)
{
if(inputString[i] == ';')
{
ages.push_back(word);
word = "";
}
else if (inputString[i] == ',')
{
names.push_back(word);
word = "";
}
else
{
word = word + inputString[i];
}
}
ages.push_back(word);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.