How to parse complex string with C++?

前端 未结 4 2099
小蘑菇
小蘑菇 2021-02-02 01:02

I\'m trying to figure out how could I parse this string using \"sstream\" and C++

The format of it is: \"string,int,int\".

I need to be able to ass

4条回答
  •  栀梦
    栀梦 (楼主)
    2021-02-02 01:27

    Here's a useful tokenization function. It doesn't use streams, but can easily perform the task you require by splitting the string on commas. Then you can do whatever you want with the resulting vector of tokens.

    /// String tokenizer.
    ///
    /// A simple tokenizer - extracts a vector of tokens from a 
    /// string, delimited by any character in delims.
    ///
    vector tokenize(const string& str, const string& delims)
    {
        string::size_type start_index, end_index;
        vector ret;
    
        // Skip leading delimiters, to get to the first token
        start_index = str.find_first_not_of(delims);
    
        // While found a beginning of a new token
        //
        while (start_index != string::npos)
        {
            // Find the end of this token
            end_index = str.find_first_of(delims, start_index);
    
            // If this is the end of the string
            if (end_index == string::npos)
                end_index = str.length();
    
            ret.push_back(str.substr(start_index, end_index - start_index));
    
            // Find beginning of the next token
            start_index = str.find_first_not_of(delims, end_index);
        }
    
        return ret;
    }
    

提交回复
热议问题