【问题标题】:How to extract substring by using start and end delimiters in C++如何在 C++ 中使用开始和结束分隔符提取子字符串
【发布时间】:2021-04-29 14:44:16
【问题描述】:

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

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++ 中复制它?

【问题讨论】:

  • Find第一个digit,然后用std::stoi转换数字。
  • 或使用正则表达式:stackoverflow.com/questions/30073839/…
  • 180 在这里究竟代表什么? IE。在路径为../45/123/4data25Position180_1.csv 的假设示例中,您要查找的数字是多少?
  • @SergeyA 这不会发生。它只会在帖子中指定。
  • 而不仅仅是遵循@Someprogrammerdude 的建议。

标签: c++ string parsing


【解决方案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;
}

【讨论】:

    【解决方案2】:
    #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());
    }
    

    【讨论】:

      猜你喜欢
      • 2018-11-11
      • 1970-01-01
      • 2018-12-05
      • 2014-12-29
      • 2018-11-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多