提问者:小点点

C++中如何使用起始和结束分隔符提取子字符串


我有一个来自命令行输入的字符串,如下所示:

string input = cmd_line.get_arg("-i"); // Filepath for offline mode

这看起来像一个文件,如下所示:

input = "../../dataPosition180.csv"

我想提取180并存储为int

在python中,我只需要:

data = int(input.split('Position')[-1].split('.csv')[0])

我如何在C++中复制它?


共1个答案

匿名用户

这里有一个(有点冗长的)解决方案:

#include <string>
#include <iostream>

using namespace std;

int main() {
  string input = "../../dataPosition180.csv";
  // We add 8 because we want the position after "Position", which has length 8.
  int start = input.rfind("Position") + 8;
  int end = input.find(".csv");
  int length = end - start;
  int part = atoi(input.substr(start, length).c_str());
  cout << part << endl;
  return 0;
}

相关问题


MySQL Query : SELECT * FROM v9_ask_question WHERE 1=1 AND question regexp '(c++|中|起始|结束|分隔符|提取|子|字符串)' ORDER BY qid DESC LIMIT 20
MySQL Error : Got error 'repetition-operator operand invalid' from regexp
MySQL Errno : 1139
Message : Got error 'repetition-operator operand invalid' from regexp
Need Help?