| 1 | // LAF Base Library |
| 2 | // Copyright (c) 2001-2016 David Capello |
| 3 | // |
| 4 | // This file is released under the terms of the MIT license. |
| 5 | // Read LICENSE.txt for more information. |
| 6 | |
| 7 | #ifdef HAVE_CONFIG_H |
| 8 | #include "config.h" |
| 9 | #endif |
| 10 | |
| 11 | #include "base/split_string.h" |
| 12 | |
| 13 | #include <algorithm> |
| 14 | |
| 15 | namespace { |
| 16 | |
| 17 | struct is_separator { |
| 18 | const std::string* separators; |
| 19 | |
| 20 | is_separator(const std::string* seps) : separators(seps) { |
| 21 | } |
| 22 | |
| 23 | bool operator()(std::string::value_type chr) |
| 24 | { |
| 25 | for (std::string::const_iterator |
| 26 | it = separators->begin(), |
| 27 | end = separators->end(); it != end; ++it) { |
| 28 | if (chr == *it) |
| 29 | return true; |
| 30 | } |
| 31 | return false; |
| 32 | } |
| 33 | }; |
| 34 | |
| 35 | } |
| 36 | |
| 37 | void base::split_string(const std::string& string, |
| 38 | std::vector<std::string>& parts, |
| 39 | const std::string& separators) |
| 40 | { |
| 41 | std::size_t elements = 1 + std::count_if(string.begin(), string.end(), is_separator(&separators)); |
| 42 | parts.reserve(elements); |
| 43 | |
| 44 | std::size_t beg = 0, end; |
| 45 | while (true) { |
| 46 | end = string.find_first_of(separators, beg); |
| 47 | if (end != std::string::npos) { |
| 48 | parts.push_back(string.substr(beg, end - beg)); |
| 49 | beg = end+1; |
| 50 | } |
| 51 | else { |
| 52 | parts.push_back(string.substr(beg)); |
| 53 | break; |
| 54 | } |
| 55 | } |
| 56 | } |
| 57 | |