简体   繁体   中英

C++ reading string using more delimiters

I'm quite new to c++. My problem is that I have a string that can be any length and ends with \n. For example:

const string s = "Daniel,20;Michael,99\n" (It's always "name,age;name,age;name,age.............\n")

and I want to separate name and age and put it into two vectors so it can be stored. But I dont know how to manage string with more separators. So the example would be separated like this:

Vector name contains {Daniel,Michael}

Vector age contains {20,99}

You can use stringstream and getline for this purpose, but since you have a very specific format, simple std::string::find is likely to fix your issue. Here is a simple example:

#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);

}

Sorry my C++ skills have faded, but this is what I would do:-

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM