1 /*******************************************************************************
2  * tlx/string/split_view.hpp
3  *
4  * Split a std::string and call a functor with tlx::string_view for each part.
5  *
6  * Part of tlx - http://panthema.net/tlx
7  *
8  * Copyright (C) 2016-2019 Timo Bingmann <tb@panthema.net>
9  *
10  * All rights reserved. Published under the Boost Software License, Version 1.0
11  ******************************************************************************/
12 
13 #ifndef TLX_STRING_SPLIT_VIEW_HEADER
14 #define TLX_STRING_SPLIT_VIEW_HEADER
15 
16 #include <tlx/container/string_view.hpp>
17 
18 namespace tlx {
19 
20 //! \addtogroup tlx_string
21 //! \{
22 //! \name Split and Join
23 //! \{
24 
25 /*!
26  * Split the given string at each separator character into distinct substrings,
27  * and call the given callback with a StringView for each substring. Multiple
28  * consecutive separators are considered individually and will result in empty
29  * split substrings.
30  *
31  * \param str       string to split
32  * \param sep       separator character
33  * \param callback  callback taking StringView of substring
34  * \param limit     maximum number of parts returned
35  */
36 template <typename Functor>
37 static inline
split_view(char sep,const std::string & str,Functor && callback,std::string::size_type limit=std::string::npos)38 void split_view(
39     char sep, const std::string& str, Functor&& callback,
40     std::string::size_type limit = std::string::npos) {
41 
42     if (limit == 0) {
43         callback(StringView(str.begin(), str.end()));
44         return;
45     }
46 
47     std::string::size_type count = 0;
48     auto it = str.begin(), last = it;
49 
50     for ( ; it != str.end(); ++it)
51     {
52         if (*it == sep)
53         {
54             if (count == limit)
55             {
56                 callback(StringView(last, str.end()));
57                 return;
58             }
59             callback(StringView(last, it));
60             ++count;
61             last = it + 1;
62         }
63     }
64     callback(StringView(last, it));
65 }
66 
67 //! \}
68 //! \}
69 
70 } // namespace tlx
71 
72 #endif // !TLX_STRING_SPLIT_VIEW_HEADER
73 
74 /******************************************************************************/
75