LAZR.PW
Stuff I'm working on.

Saturday, 2 February 2013

CSV(or any specified char separator) to a vector of strings

#include <string>  
#include <vector>  
#include <sstream>  
  
void splitStr(const std::string &source, char key, std::vector<std::string>& result)  
{  
    std::stringstream ss(source);  
  
    while(ss.good())  
    {  
        std::string substr;  
        std::getline(ss, substr, key); // Get substring separated by delimiter key  
        result.push_back(substr);  
    }  
} 
This will basically loop through the string splitting it by a specified key and push each string into a vector of strings. With C++11 it may be just as efficient to create the vector inside the function and just return it; as vectors utilize R-value referencing in their move constructor (A modified copy constructor for a shallow copy that moves a reference to the data rather than the data itself).

No comments:

Post a Comment