1 // Copyright 2015 The Weave Authors. All rights reserved. 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 <string.h> 6 #include <algorithm> 7 #include <utility> 8 9 #include <base/strings/string_util.h> 10 11 #include "src/string_utils.h" 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 for (std::string::size_type i = 0;;) { 49 const std::string::size_type pos = 50 delimiter.empty() ? (i + 1) : str.find(delimiter, i); 51 std::string tmp_str{str.substr(i, pos - i)}; 52 if (trim_whitespaces) 53 base::TrimWhitespaceASCII(tmp_str, base::TRIM_ALL, &tmp_str); 54 if (!tmp_str.empty() || !purge_empty_strings) 55 tokens.emplace_back(std::move(tmp_str)); 56 if (pos >= str.size()) 57 break; 58 i = pos + delimiter.size(); 59 } 60 return tokens; 61 } 62 63 std::pair<std::string, std::string> SplitAtFirst(const std::string& str, 64 const std::string& delimiter, 65 bool trim_whitespaces) { 66 std::pair<std::string, std::string> pair; 67 SplitAtFirst(str, delimiter, &pair.first, &pair.second, trim_whitespaces); 68 return pair; 69 } 70 71 } // namespace weave 72