用不同的分隔符分割字符串

问题描述 投票:0回答:2

具有以下输入类型:

add name, breed, birthDate, vaccinationsCount, photograph

(例如add boo, yorkshire terrier, 01-13-2017, 7, boo puppy.jpg

我想分割此字符串以获取其参数,但它不起作用。

我的代码如下:

getline(cin, listOfCommands);
string functionToApply = listOfCommands.substr(0, listOfCommands.find(" "));
int position = listOfCommands.find(" ");
listOfCommands.erase(0, position + 1);
cout << listOfCommands;
if (functionToApply == "exit")
    break;
else if (functionToApply == "add")
{
    position = listOfCommands.find(", ");
    string name = listOfCommands.substr(0, position);
    listOfCommands.erase(0, position + 1);
    position = listOfCommands.find(", ");
    string breed = listOfCommands.substr(0, position);
    listOfCommands.erase(0, position + 2);
    position = listOfCommands.find(", ");
    string birthDate = listOfCommands.substr(0, position);
    listOfCommands.erase(0, position + 2);
    position = listOfCommands.find(", ");
    string nrShorts = listOfCommands.substr(0, position);
    listOfCommands.erase(0, position + 2);
    string photo = listOfCommands;
}

有人可以帮我吗?

c++ string split stl
2个回答
0
投票

对于此示例,我使用带有自定义定界符的std::getlinestd::stringstream来帮助解析输入的流,并使用std::vector来存储参数(如果愿意,可以将它们分配给为其创建的变量) :

Live sample

#include <iostream> 
#include <sstream>
#include <vector>

int main ()
{
    std::string listOfCommands, temp;
    std::vector<std::string> args; //container for the arguments

    //your code to treat 'add' command (untouched)
    getline(std::cin, listOfCommands);
    std::string functionToApply = listOfCommands.substr(0, listOfCommands.find(" "));
    int position = listOfCommands.find(" ");
    listOfCommands.erase(0, position + 1);

    //parse comma separated arguments
    std::stringstream ss(listOfCommands);

    while(getline(ss, temp, ',')){

        while(*(temp.begin()) == ' ')
            temp.erase(temp.begin()); //remove leading whitespaces

        args.push_back(temp); //add to container
    }

    //test print
    for(std::string str : args){
        std::cout << str << std::endl;
    }

    return 0;
}

0
投票

尝试regex_token_iterator

#include <regex>

const int split_constant = -1;
std::vector<std::string> args(
  std::sregex_token_iterator(listOfCommands.begin(), 
                             listOfCommands.end(), 
                             std::regex(", "), 
                             split_constant),
  std::sregex_token_iterator());

当然,您不必将标记保存在向量中,也可以对其进行迭代:

auto iter = std::sregex_token_iterator(listOfCommands.begin(), 
                                       listOfCommands.end(), 
                                       std::regex(", "), 
                                       split_constant);
const string functionToApply = *iter++;
if (functionToApply == "exit") break;
const string name  = *iter++;
const string breed = *iter++;
// etc.
© www.soinside.com 2019 - 2024. All rights reserved.