c++ - C++ 中子字符串方法的问题

标签 c++ string substring

<分区>

给定字符串 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

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

任何输入将不胜感激

最佳答案

substr需要一个索引和一个长度。

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

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

关于c++ - C++ 中子字符串方法的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51199281/

相关文章:

c++ - FFmpeg API 示例 (encode_video.c) 无法正常工作

c - char* 操作期间的内存泄漏

Ruby 字符串 #{} 不起作用

swift - 如何在另一个字符串中找到所有出现的字符串子集并将它们替换为其他内容? (例如 : Emote replacement)

C++ 引用、地址、指针

c++ - 如何从消息队列接收动态长度数据?

c++ - 创建邻接表时输出不一致

java - 如何在java中使用正则表达式和修剪从字符串中删除不必要的空格

Java字符串获取空格后的字符

c# - 将 MySQL 查询转换为 Sqlite (SUBSTRING_INDEX)