Vitaly Buka | 4615e0d | 2015-10-14 15:35:12 -0700 | [diff] [blame] | 1 | // Copyright 2015 The Weave Authors. All rights reserved. |
Vitaly Buka | 24d6fd5 | 2015-08-13 23:22:48 -0700 | [diff] [blame] | 2 | // Use of this source code is governed by a BSD-style license that can be |
| 3 | // found in the LICENSE file. |
| 4 | |
| 5 | #include <algorithm> |
| 6 | #include <string.h> |
| 7 | #include <utility> |
| 8 | |
| 9 | #include <base/strings/string_util.h> |
| 10 | |
Stefan Sauer | 2d16dfa | 2015-09-25 17:08:35 +0200 | [diff] [blame] | 11 | #include "src/string_utils.h" |
Vitaly Buka | 24d6fd5 | 2015-08-13 23:22:48 -0700 | [diff] [blame] | 12 | |
| 13 | namespace weave { |
| 14 | |
| 15 | namespace { |
| 16 | |
| 17 | bool SplitAtFirst(const std::string& str, |
| 18 | const std::string& delimiter, |
| 19 | std::string* left_part, |
| 20 | std::string* right_part, |
| 21 | bool trim_whitespaces) { |
| 22 | bool delimiter_found = false; |
| 23 | std::string::size_type pos = str.find(delimiter); |
| 24 | if (pos != std::string::npos) { |
| 25 | *left_part = str.substr(0, pos); |
| 26 | *right_part = str.substr(pos + delimiter.size()); |
| 27 | delimiter_found = true; |
| 28 | } else { |
| 29 | *left_part = str; |
| 30 | right_part->clear(); |
| 31 | } |
| 32 | |
| 33 | if (trim_whitespaces) { |
| 34 | base::TrimWhitespaceASCII(*left_part, base::TRIM_ALL, left_part); |
| 35 | base::TrimWhitespaceASCII(*right_part, base::TRIM_ALL, right_part); |
| 36 | } |
| 37 | |
| 38 | return delimiter_found; |
| 39 | } |
| 40 | |
| 41 | } // namespace |
| 42 | |
| 43 | std::vector<std::string> Split(const std::string& str, |
| 44 | const std::string& delimiter, |
| 45 | bool trim_whitespaces, |
| 46 | bool purge_empty_strings) { |
| 47 | std::vector<std::string> tokens; |
| 48 | if (str.empty()) |
| 49 | return tokens; |
| 50 | |
| 51 | for (std::string::size_type i = 0;;) { |
| 52 | const std::string::size_type pos = |
| 53 | delimiter.empty() ? (i + 1) : str.find(delimiter, i); |
| 54 | std::string tmp_str{str.substr(i, pos - i)}; |
| 55 | if (trim_whitespaces) |
| 56 | base::TrimWhitespaceASCII(tmp_str, base::TRIM_ALL, &tmp_str); |
| 57 | if (!tmp_str.empty() || !purge_empty_strings) |
| 58 | tokens.emplace_back(std::move(tmp_str)); |
| 59 | if (pos >= str.size()) |
| 60 | break; |
| 61 | i = pos + delimiter.size(); |
| 62 | } |
| 63 | return tokens; |
| 64 | } |
| 65 | |
| 66 | std::pair<std::string, std::string> SplitAtFirst(const std::string& str, |
| 67 | const std::string& delimiter, |
| 68 | bool trim_whitespaces) { |
| 69 | std::pair<std::string, std::string> pair; |
| 70 | SplitAtFirst(str, delimiter, &pair.first, &pair.second, trim_whitespaces); |
| 71 | return pair; |
| 72 | } |
| 73 | |
| 74 | } // namespace weave |