user2840470
user2840470

Reputation: 969

How can I split a string (with no spaces) into separate strings?

I am trying to read in multiple strings that belong to a vector of structs from one line, but the string has no spaces. Here is basically my problem:

File data:

G01G02G03G04G05

And when I read it in:

for (int i=0;i<5;i++)
    File>>vector.at(i).string

And what I get is the first string in the vector as

G01G02G03G04G05

Where I would rather have it:

vector(1)=G01;
vector(2)=G02... and so on

Sorry forgot some information, Im in C++ vs2010 and it is always three characters long, starting with either G,R,C,D

Upvotes: 2

Views: 181

Answers (3)

goji
goji

Reputation: 7092

This is how I would split the substrings into a vector:

std::vector<std::string> parseData(const std::string& s)
{
    if (s.size() % 3 != 0) {
        throw std::runtime_error("incorrect data length");
    }

    std::vector<std::string> result;`enter code here`
    for (size_t i = 0; i <= s.size() - 3; i += 3) {
        result.emplace_back(s, i, 3);
    }

    return result;
}

See coliru for a full compilable demo.

You could generalise this to support any length sub-strings.

Upvotes: 1

LihO
LihO

Reputation: 42083

"Yes it is always three characters long"

Then it could look the following way:

std::vector<std::string> tokens;

std::string line;
if (getline(cin, line)) {
    for (size_t i = 0; i < line.size(); i += 3) {
        tokens.push_back(line.substr(i, 3));
    }
}

Upvotes: 1

pm100
pm100

Reputation: 50110

C++ cannot know that you want it chopped up like that; you could equally want each character in a separate string. of in bunches of 2 characters,....

Read it into one string then chop the string up

for (int i = 0; i < 5; i++)
{
     std::string bit = instr.substr(i * 3,3);
     vec.push_back(bit);
}

Upvotes: 1

Related Questions