【问题标题】:Why doesn't substr stop at delimiter?为什么 substr 不在分隔符处停止?
【发布时间】:2017-05-25 06:43:49
【问题描述】:

我是 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 

【问题讨论】:

    标签: c++ delimiter substr


    【解决方案1】:

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

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

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

    【讨论】:

    • 哦...我应该阅读参考资料两次...不过还是谢谢。我现在明白了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-07-21
    • 2014-04-12
    • 1970-01-01
    • 2023-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多