connor449
connor449

Reputation: 1679

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.

In python, I would just do:

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

How do I replicate this in C++?

Upvotes: 0

Views: 641

Answers (2)

Daniel Zin
Daniel Zin

Reputation: 499

#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());
}

Upvotes: 0

Marcelo Menegali
Marcelo Menegali

Reputation: 866

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

Upvotes: 1

Related Questions