为什么 substr 不在定界符处停止?

Why doesn't substr stop at delimiter?

我是 C++ 的新手所以如果它是愚蠢的东西,请不要苛刻。

我试图将一个字符串分成两部分。我能够使用 substr 正确地分隔第一部分,但是由于某种原因,当我尝试分隔第二部分时,它也会在分隔符之后获取所有内容。我检查它是否识别出我试图阻止它的位置 (pos1) 并且它是正确的位置,但之后它仍然需要一切。

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

输出:

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 

substr的第二个参数是字符数,不是最后的索引。您需要将第二次调用更改为:

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

顺便说一下,严格来说,在第一次调用 substr 时,您实际上想要使用 pos-1 个字符,除非您想要结果字符串中的 space。