Back to home page

Project CMSSW displayed by LXR

 
 

    


File indexing completed on 2024-04-06 12:11:49

0001 #ifndef split_h
0002 #define split_h
0003 
0004 #include <string>
0005 
0006 // template <typename E, typename C>
0007 // size_t split(std::basic_string<E> const& s,
0008 //              C &container,
0009 //              E const delimiter,
0010 //              bool keepBlankFields = true)
0011 //
0012 // Function that splits a string 's' at the occurrences of 'delimiter', and adds the pieces at the end of 'container'.
0013 // // If keepBlankFields is false (the default), consecutive delimiters are treated as a single field separator; otherwise, they produce empty fields.
0014 //
0015 // The function is templated on
0016 //   the character type E (used both for string and delimiter)
0017 //   the container type C (container::value_type must be constructible from std::basic_string<E>)
0018 //
0019 // see: http://www.codeproject.com/KB/stl/Split_string.aspx
0020 
0021 template <typename E, typename C>
0022 size_t split(std::basic_string<E> const& s,
0023              C &container,
0024              E const delimiter,
0025              bool keepBlankFields = true)
0026 {
0027     size_t n = 0;
0028     typename std::basic_string<E>::const_iterator it = s.begin(), end = s.end(), first;
0029     for (first = it; it != end; ++it)
0030     {
0031         // Examine each character and if it matches the delimiter
0032         if (delimiter == *it)
0033         {
0034             if (keepBlankFields || first != it)
0035             {
0036                 // extract the current field from the string and
0037                 // append the current field to the given container
0038                 container.push_back(std::basic_string<E>(first, it));
0039                 ++n;
0040 
0041                 // skip the delimiter
0042                 first = it + 1;
0043             }
0044             else
0045             {
0046                 ++first;
0047             }
0048         }
0049     }
0050     if (keepBlankFields || first != it)
0051     {
0052         // extract the last field from the string and
0053         // append the last field to the given container
0054         container.push_back(std::basic_string<E>(first, it));
0055         ++n;
0056     }
0057     return n;
0058 }
0059 
0060 #endif // split_h