Search code examples
c++delimitersubstr

Why doesn't substr stop at delimiter?


I'm new to C++ so if it's something stupid, please don't be too harsh.

I'm trying to separate a string into two parts. I'm able to separate the first part using substr properly but for some reason when I try separating the second part it takes everything after the delimiter as well. I checked to see if it recognized where I was trying to stop it (pos1) and it's the right position, but it still takes everything afterwards.

for(u_int i = 0; i < eachPerson.size(); i++)
{
    string temp, first, last;
    u_int pos, pos1;
    temp = eachPerson[i];
    pos = temp.find_first_of(' ');
    pos1 = temp.find_first_of(':');
    cout << pos1 << endl;
    first = temp.substr(0, pos);
    last = temp.substr(pos+1, pos1);
    cout << "First: " << first << endl
         << "Last: " << last << endl;
}

Output:

John Doe: 20 30 40 <- How each line looks before it's separated
Jane Doe: 60 70 80
8 <- Location of delimiter
First: John <- first
Last: Doe: 20 <- last
8
First: Jane
Last: Doe: 60 

Solution

  • The second argument of substr is the number of the characters, not the final index. You need to change the second call to:

    last = temp.substr(pos+1, pos1-pos-1);
    

    By the way, to be strict, in the first call to substr, you actually want to take pos-1 characters, unless you want the space in the resulting string.