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

Splitting a line into token with find()

本文关键字:拆分 一行 find 使用      更新时间:2023-10-16

我想拆分这一行:

cmd1; cmd2; 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/

std::basic_string::substr 的第二个参数需要一个长度,指示从 start_pos 开始的子字符串的长度。

string substr (size_t pos = 0, size_t len = npos) const;

所以,你实际上应该替换

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

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