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

后端 未结 20 2441
时光说笑
时光说笑 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:05

    Here's my take on this. It handles the edge cases and takes an optional parameter to remove empty entries from the results.

    bool endsWith(const std::string& s, const std::string& suffix)
    {
        return s.size() >= suffix.size() &&
               s.substr(s.size() - suffix.size()) == suffix;
    }
    
    std::vector split(const std::string& s, const std::string& delimiter, const bool& removeEmptyEntries = false)
    {
        std::vector tokens;
    
        for (size_t start = 0, end; start < s.length(); start = end + delimiter.length())
        {
             size_t position = s.find(delimiter, start);
             end = position != string::npos ? position : s.length();
    
             std::string token = s.substr(start, end - start);
             if (!removeEmptyEntries || !token.empty())
             {
                 tokens.push_back(token);
             }
        }
    
        if (!removeEmptyEntries &&
            (s.empty() || endsWith(s, delimiter)))
        {
            tokens.push_back("");
        }
    
        return tokens;
    }
    

    Examples

    split("a-b-c", "-"); // [3]("a","b","c")
    
    split("a--c", "-"); // [3]("a","","c")
    
    split("-b-", "-"); // [3]("","b","")
    
    split("--c--", "-"); // [5]("","","c","","")
    
    split("--c--", "-", true); // [1]("c")
    
    split("a", "-"); // [1]("a")
    
    split("", "-"); // [1]("")
    
    split("", "-", true); // [0]()
    

提交回复
热议问题