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.
5 #include "base/string_split.h"
7 #include "base/string_util.h"
11 bool SplitStringIntoKeyValues(
12 const std::string
& line
,
13 char key_value_delimiter
,
14 std::string
* key
, std::vector
<std::string
>* values
) {
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
24 key
->assign(line
, 0, end_key_pos
);
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
33 std::string
values_string(remains
, begin_values_pos
,
34 remains
.size() - begin_values_pos
);
36 // Construct the values vector.
37 values
->push_back(values_string
);
41 bool 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
) {
48 std::vector
<std::string
> pairs
;
49 SplitString(line
, key_value_pair_delimiter
, &pairs
);
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.
59 std::vector
<std::string
> value
;
60 if (!SplitStringIntoKeyValues(pairs
[i
],
63 // Don't return here, to allow for keys without associated
64 // values; just record that our split failed.
67 DCHECK_LE(value
.size(), 1U);
68 kv_pairs
->push_back(make_pair(key
, value
.empty()? "" : value
[0]));