我是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的第二个参数是字符数,而不是最终索引。您需要将第二个 call 更改为:

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

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

09-10 02:11
查看更多