string_split.cc revision c407dc5cd9bdc5668497f21b26b09d988ab439de
1// Copyright (c) 2010 The Chromium 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 "base/string_split.h"
6
7#include "base/string_util.h"
8
9namespace base {
10
11bool SplitStringIntoKeyValues(
12    const std::string& line,
13    char key_value_delimiter,
14    std::string* key, std::vector<std::string>* values) {
15  key->clear();
16  values->clear();
17
18  // Find the key string.
19  size_t end_key_pos = line.find_first_of(key_value_delimiter);
20  if (end_key_pos == std::string::npos) {
21    DLOG(INFO) << "cannot parse key from line: " << line;
22    return false;    // no key
23  }
24  key->assign(line, 0, end_key_pos);
25
26  // Find the values string.
27  std::string remains(line, end_key_pos, line.size() - end_key_pos);
28  size_t begin_values_pos = remains.find_first_not_of(key_value_delimiter);
29  if (begin_values_pos == std::string::npos) {
30    DLOG(INFO) << "cannot parse value from line: " << line;
31    return false;   // no value
32  }
33  std::string values_string(remains, begin_values_pos,
34                            remains.size() - begin_values_pos);
35
36  // Construct the values vector.
37  values->push_back(values_string);
38  return true;
39}
40
41bool SplitStringIntoKeyValuePairs(
42    const std::string& line,
43    char key_value_delimiter,
44    char key_value_pair_delimiter,
45    std::vector<std::pair<std::string, std::string> >* kv_pairs) {
46  kv_pairs->clear();
47
48  std::vector<std::string> pairs;
49  SplitString(line, key_value_pair_delimiter, &pairs);
50
51  bool success = true;
52  for (size_t i = 0; i < pairs.size(); ++i) {
53    // Empty pair. SplitStringIntoKeyValues is more strict about an empty pair
54    // line, so continue with the next pair.
55    if (pairs[i].empty())
56      continue;
57
58    std::string key;
59    std::vector<std::string> value;
60    if (!SplitStringIntoKeyValues(pairs[i],
61                                  key_value_delimiter,
62                                  &key, &value)) {
63      // Don't return here, to allow for keys without associated
64      // values; just record that our split failed.
65      success = false;
66    }
67    DCHECK_LE(value.size(), 1U);
68    kv_pairs->push_back(make_pair(key, value.empty()? "" : value[0]));
69  }
70  return success;
71}
72
73}  // namespace base
74