shadowm

Untitled

Aug 14th, 2014
333
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.02 KB | None | 0 0
  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.         if (p == q) {
  24.             // An empty fragment.
  25.             if (!ignore_empty) {
  26.                 res.push_back("");
  27.             }
  28.             q += delimiter.length();
  29.         } else {
  30.             // Maybe an empty fragment
  31.             std::string sub = str.substr(q, p - q);
  32.  
  33.             if (strip_spaces) {
  34.                 strip(sub);
  35.             }
  36.  
  37.             if (!ignore_empty || !sub.empty()) {
  38.                 res.push_back(std::move(sub));
  39.             }
  40.  
  41.             q = p + delimiter.length();
  42.         }
  43.     }
  44.  
  45.     return res;
  46. }
Advertisement
Add Comment
Please, Sign In to add comment