简体   繁体   English

如何使用 C++ 中的开始和结束分隔符来提取 substring

[英]How to extract substring by using start and end delimiters in C++

I have a string from command line input, like this:我有一个来自命令行输入的字符串,如下所示:

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

This looks like a file as below:这看起来像一个文件,如下所示:

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

I want to extract out the 180 and store as an int .我想提取180并存储为int

In python, I would just do:在 python 中,我会这样做:

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

How do I replicate this in C++?如何在 C++ 中复制它?

Here's a (somewhat verbose) solution:这是一个(有点冗长的)解决方案:

#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;
}
#include <string>
#include <regex>

using namespace std;

int getDataPositionId (const string& input){
    regex mask ("dataPosition(\\d+).csv");
    smatch match;    
    if (! regex_search(input, match, mask)){
        throw runtime_error("invalid input");
    }
    return std::stoi(match[1].str());
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM