有选择地在空格上拆分字符串

时间:2013-06-18 19:34:09

标签: c++

我的命令是:

move 1 "South Africa" "Europe"

代码:

do 
{
  cut = text.find(' ');
  if (cut == string::npos) 
  {
    params.push_back(text);
  } 
  else 
  {
    params.push_back(text.substr(0, cut));
    text = text.substr(cut + 1);
  }
}  
while (cut != string::npos);

问题在于South Africa被分为SouthAfrica,我需要将其保留为South Africa

切割后的参数:

1, South, Africa, Europe

我需要它:

1, South Africa, Europe

我该怎么做?用正则表达式?

命令的另一个例子:

move 3 "New Island" "South Afrika"

我的代码在''之后切断,我需要在我推回的参数中

3, New Island, South Africa

我的代码制作:

3,"New,Island","South,Africa"

1 个答案:

答案 0 :(得分:1)

您可以使用std::stringstreamstd::getline

来解析字符串
#include <iostream>
#include <sstream>
#include <string>

int main() {
    std::string text("move 3 \"New Island\" \"South Afrika\"");
    std::string command, count, country1, country2, temp;
    std::stringstream ss(text);

    ss >> command >> count;
    ss.str("");
    ss << text;
    std::getline(ss, temp, '\"');
    std::getline(ss, country1, '\"');
    std::getline(ss, temp, '\"');
    std::getline(ss, country2, '\"');

    std::cout << command << ", " << count << ", " <<
        country1 << ", " << country2 << std::endl;
    return 0;
}