【问题标题】:Splitting a line into token with find()使用 find() 将一行拆分为标记
【发布时间】:2015-04-26 10:21:10
【问题描述】:

我想分割这条线:

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

【问题讨论】:

    标签: c++ split find


    【解决方案1】:

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

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

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

    【讨论】:

    • 哦,是的,我太笨了,非常感谢!我会在 6 分钟内“接受”你的回答 :)
    【解决方案2】:

    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));
    

    【讨论】:

      猜你喜欢
      • 2017-03-17
      • 1970-01-01
      • 2021-05-27
      • 2022-10-14
      • 1970-01-01
      • 2012-03-23
      • 2013-09-15
      • 1970-01-01
      相关资源
      最近更新 更多