c++ regex


  • 1
    S

    Inspired by the solution @StefanPochmann

    1. we join the vector of string into one string using \n
    2. regex replace the comments using empty string
    3. split the string into vector of string using \n
    class Solution {
    public:
        vector<string> removeComments(vector<string>& source) {
            stringstream ss;
            const char* delim="\n";
            copy(source.begin(),source.end(),ostream_iterator<string>(ss,delim));
            string s=ss.str();
            //cout<<s;
            regex e("//.*|/\\*(.|\n)*?\\*/");
            string ns=regex_replace(s,e,"");
            //cout<<ns;
            //split the string into vector using tokened string
            ss.str(ns);
            vector<string> ans;
            while(ss.good())
            {
                string token;
                getline(ss,token,'\n');
                if(!token.empty())
                ans.push_back(token);
            }
            //copy(ans.begin(),ans.end(),ostream_iterator<string>(cout,"\n"));
            return ans;
        }
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.