shadowm

Untitled

Aug 14th, 2014
326
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. std::vector<std::string> split(const std::string& str, const std::string& delimiter, bool ignore_empty, bool strip_spaces)
  2. {
  3.     if (str.empty()) {
  4.         return {};
  5.     }
  6.  
  7.     std::vector<std::string> res;
  8.  
  9.     for (size_t p = 0, q = 0; p < str.length(); ++p) {
  10.         if (delimiter.empty()) {
  11.             res.push_back(std::string(1, str[p]));
  12.             continue;
  13.         }
  14.  
  15.         // If we are looking at the last character we want to check if the
  16.         // remainder needs to be pushed into the result below, otherwise always
  17.         // check for the delimiter first.
  18.         if (p + 1 < str.length() &&
  19.             str.compare(p, delimiter.length(), delimiter) != 0) {
  20.             continue;
  21.         }
  22.  
  23.         std::string sub = str.substr(q, p + 1 == str.length() ? std::string::npos : p - q);
  24.  
  25.         if (strip_spaces) {
  26.             strip(sub);
  27.         }
  28.  
  29.         if (!ignore_empty || !sub.empty()) {
  30.             res.push_back(std::move(sub));
  31.         }
  32.  
  33.         q = p + delimiter.length();
  34.     }
  35.  
  36.     return res;
  37. }
Advertisement
Add Comment
Please, Sign In to add comment