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() を使用して部分を抽出できます。残念ながら、可能性のあるセパレーターは 1 つではなく、2 つ (+ と -) あります。
  • 文字列で直接正規表現を使用することを選択できます
  • find_first_of()と を使用して、最終的に文字列を分割できます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区切り文字は 1 つしか使用できないため、文字列を個別に検索して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 に答える