【问题标题】:Issues with the substring method in C++ [duplicate]C ++中子字符串方法的问题[重复]
【发布时间】:2018-07-05 20:20:40
【问题描述】:

给定字符串 IP 作为输入

int index, i=0;
string substr;
while(i!=-1 && IPv4){
            index=IP.find(".",i+1);
            substr=IP.substr(i,index);
            cout << substr << " found at index " << index << " with i= "<<i << endl;
            i=index;
        }

输入:“172.16.254.1”

预期输出:

172 found at index 3 with i= 0
.16 found at index 6 with i= 3
.254 found at index 10 with i= 6
.1 found at index -1 with i= 10

结果输出:

172 found at index 3 with i= 0
.16.25 found at index 6 with i= 3
.254.1 found at index 10
.1 found at index -1 with i= 10

所以算法使用的值应该是正确的,但我得到了错误的子字符串。

任何意见将不胜感激

【问题讨论】:

标签: c++ string substring


【解决方案1】:

substr 采用索引和长度。

另外,将变量命名为与成员函数相同可能不是一个好主意。你可能想要:

ip_chunk = IP.substr(i, index - i);

【讨论】:

    猜你喜欢
    • 2021-10-01
    • 1970-01-01
    • 2014-04-12
    • 2016-10-05
    • 1970-01-01
    • 2010-12-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多