gpt4 book ai didi

c++ - 使用 find() 将一行拆分为标记

转载 作者:行者123 更新时间:2023-11-28 00:16:36 25 4
gpt4 key购买 nike

我想拆分这条线:

cmd1;命令2; cmd3

分成3串我会存入一个列表。喜欢

cmd1
cmd2
cmd3

所以我写了这段代码:

main.cpp

#include <string>
#include <iostream>
#include <list>

int main()
{
std::string line("cmd1; cmd2; cmd3");
std::list<std::string> l;
size_t pos = 0;
size_t ex_pos = 0;

while ((pos = line.find(';', ex_pos)) != std::string::npos)
{
l.push_back(line.substr(ex_pos, pos));
ex_pos = pos + 2;
}
l.push_back(line.substr(ex_pos, pos));
for (std::list<std::string>::iterator it = l.begin(); it != l.end(); ++it)
{
std::cout << *it << std::endl;
}
return (0);
}

但我不知道为什么它返回我:

cmd1
cmd2; cmd3
cmd3

最佳答案

substr 的第二个参数不是要复制的 lat 字符的索引。它是目标子串的长度。

l.push_back(line.substr(ex_pos, pos-ex_pos));

http://www.cplusplus.com/reference/string/string/substr/

关于c++ - 使用 find() 将一行拆分为标记,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29876415/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com