2

我正在尝试从myString1使用中提取值,std::stringstream如下所示:

// Example program
#include <iostream>
#include <string>
#include <sstream>

using namespace std;

int main()
{
  string myString1 = "+50years";
  string myString2 = "+50years-4months+3weeks+5minutes";

  stringstream ss (myString1);

  char mathOperator;
  int value;
  string timeUnit;

  ss >> mathOperator >> value >> timeUnit;

  cout << "mathOperator: " << mathOperator << endl;
  cout << "value: " << value << endl;
  cout << "timeUnit: " << timeUnit << endl;
}

输出:

mathOperator: +
value: 50
timeUnit: years

在输出中,您可以看到我成功提取了我需要的值、数学运算符、值和时间单位。

有没有办法做同样的事情myString2?也许在一个循环中?我可以提取数学运算符,值,但时间单位只是提取其他所有内容,我想不出办法解决这个问题。非常感激。

4

3 回答 3

4

问题是 timeUnit 是一个字符串,所以>>会提取任何内容,直到第一个空格,你的字符串中没有。

备择方案:

  • 您可以使用 getline() 提取部分,它会提取字符串直到找到分隔符。不幸的是,您没有一个潜在的分隔符,而是 2(+ 和 -)。
  • 您可以选择直接在字符串上使用正则表达式
  • 您最终可以使用find_first_of()and拆分字符串substr()

作为说明,这里是正则表达式的示例:

  regex rg("([\\+-][0-9]+[A-Za-z]+)", regex::extended);
  smatch sm;
  while (regex_search(myString2, sm, rg)) {
      cout <<"Found:"<<sm[0]<<endl;
      myString2 = sm.suffix().str(); 
      //... process sstring sm[0]
  }

这是一个应用您的代码提取所有元素的现场演示。

于 2015-06-17T23:05:13.343 回答
2

您可以像下面的示例中那样更健壮<regex>

#include <iostream>
#include <regex>
#include <string>

int main () {
  std::regex e ("(\\+|\\-)((\\d)+)(years|months|weeks|minutes|seconds)");
  std::string str("+50years-4months+3weeks+5minutes");
  std::sregex_iterator next(str.begin(), str.end(), e);
  std::sregex_iterator end;
  while (next != end) {
    std::smatch match = *next;
    std::cout << "Expression: " << match.str() << "\n";
    std::cout << "  mathOperator : " << match[1] << std::endl;
    std::cout << "  value        : " << match[2] << std::endl;
    std::cout << "  timeUnit     : " << match[4] << std::endl;
    ++next;
  }
}

输出:

Expression: +50years
  mathOperator : +
  value        : 50
  timeUnit     : years
Expression: -4months
  mathOperator : -
  value        : 4
  timeUnit     : months
Expression: +3weeks
  mathOperator : +
  value        : 3
  timeUnit     : weeks
Expression: +5minutes
  mathOperator : +
  value        : 5
  timeUnit     : minutes

现场演示

于 2015-06-17T23:40:20.410 回答
1

我会使用getline,timeUnit但由于getline只能使用一个分隔符,我会单独搜索字符串mathOperator并使用它:

string myString2 = "+50years-4months+3weeks+5minutes";
stringstream ss (myString2);
size_t pos=0;

ss >> mathOperator;
do
  {
    cout << "mathOperator: " << mathOperator << endl;

    ss >> value;
    cout << "value: " << value << endl;

    pos = myString2.find_first_of("+-", pos+1);
    mathOperator = myString2[pos];
    getline(ss, timeUnit, mathOperator);
    cout << "timeUnit: " << timeUnit << endl;
  }
while(pos!=string::npos);
于 2015-06-18T00:05:11.640 回答