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

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

    Answer is already there, but selected-answer uses erase function which is very costly, think of some very big string(in MBs). Therefore I use below function.

    vector split(const string& i_str, const string& i_delim)
    {
        vector result;
        
        size_t found = i_str.find(i_delim);
        size_t startIndex = 0;
    
        while(found != string::npos)
        {
            result.push_back(string(i_str.begin()+startIndex, i_str.begin()+found));
            startIndex = found + i_delim.size();
            found = i_str.find(i_delim, startIndex);
        }
        if(startIndex != i_str.size())
            result.push_back(string(i_str.begin()+startIndex, i_str.end()));
        return result;      
    }
    

提交回复
热议问题