Parse (split) a string in C++ using string delimiter (standard C++)

后端 未结 20 2122
时光说笑
时光说笑 2020-11-21 23:44

I am parsing a string in C++ using the following:

using namespace std;

string parsed,input=\"text to be parsed\";
stringstream input_stringstream(input);

i         


        
20条回答
  •  [愿得一人]
    2020-11-22 00:06

    You can also use regex for this:

    std::vector split(const std::string str, const std::string regex_str)
    {
        std::regex regexz(regex_str);
        std::vector list(std::sregex_token_iterator(str.begin(), str.end(), regexz, -1),
                                      std::sregex_token_iterator());
        return list;
    }
    

    which is equivalent to :

    std::vector split(const std::string str, const std::string regex_str)
    {
        std::sregex_token_iterator token_iter(str.begin(), str.end(), regexz, -1);
        std::sregex_token_iterator end;
        std::vector list;
        while (token_iter != end)
        {
            list.emplace_back(*token_iter++);
        }
        return list;
    }
    
    

    and use it like this :

    #include 
    #include 
    #include 
    
    std::vector split(const std::string str, const std::string regex_str)
    {   // a yet more concise form!
        return { std::sregex_token_iterator(str.begin(), str.end(), std::regex(regex_str), -1), std::sregex_token_iterator() };
    }
    
    int main()
    {
        std::string input_str = "lets split this";
        std::string regex_str = " "; 
        auto tokens = split(input_str, regex_str);
        for (auto& item: tokens)
        {
            std::cout<

    play with it online! http://cpp.sh/9sumb

    you can simply use substrings, characters,etc like normal, or use actual regular experssions to do the splitting.
    its also concize and C++11!

提交回复
热议问题