CMS 3D CMS Logo

split.h
Go to the documentation of this file.
1 #ifndef split_h
2 #define split_h
3 
4 #include <string>
5 
6 // template <typename E, typename C>
7 // size_t split(std::basic_string<E> const& s,
8 // C &container,
9 // E const delimiter,
10 // bool keepBlankFields = true)
11 //
12 // Function that splits a string 's' at the occurrences of 'delimiter', and adds the pieces at the end of 'container'.
13 // // If keepBlankFields is false (the default), consecutive delimiters are treated as a single field separator; otherwise, they produce empty fields.
14 //
15 // The function is templated on
16 // the character type E (used both for string and delimiter)
17 // the container type C (container::value_type must be constructible from std::basic_string<E>)
18 //
19 // see: http://www.codeproject.com/KB/stl/Split_string.aspx
20 
21 template <typename E, typename C>
22 size_t split(std::basic_string<E> const& s,
23  C &container,
24  E const delimiter,
25  bool keepBlankFields = true)
26 {
27  size_t n = 0;
28  typename std::basic_string<E>::const_iterator it = s.begin(), end = s.end(), first;
29  for (first = it; it != end; ++it)
30  {
31  // Examine each character and if it matches the delimiter
32  if (delimiter == *it)
33  {
34  if (keepBlankFields || first != it)
35  {
36  // extract the current field from the string and
37  // append the current field to the given container
38  container.push_back(std::basic_string<E>(first, it));
39  ++n;
40 
41  // skip the delimiter
42  first = it + 1;
43  }
44  else
45  {
46  ++first;
47  }
48  }
49  }
50  if (keepBlankFields || first != it)
51  {
52  // extract the last field from the string and
53  // append the last field to the given container
54  container.push_back(std::basic_string<E>(first, it));
55  ++n;
56  }
57  return n;
58 }
59 
60 #endif // split_h
#define end
Definition: vmac.h:39
size_t split(std::basic_string< E > const &s, C &container, E const delimiter, bool keepBlankFields=true)
Definition: split.h:22