Merged with trunk R1283.
[ardour.git] / libs / pbd / pbd / tokenizer.h
1 #ifndef PBD_TOKENIZER
2 #define PBD_TOKENIZER
3
4 #include <iterator>
5 #include <string>
6
7 #include <pbd/whitespace.h>
8
9 namespace PBD {
10
11 /**
12     Tokenize string, this should work for standard
13     strings as well as Glib::ustring. This is a bit of a hack,
14     there are much better string tokenizing patterns out there.
15         If strip_whitespace is set to true, tokens will be checked to see
16         that they still have a length after stripping.  If no length, they
17         are discarded.
18 */
19 template<typename StringType, typename Iter>
20 unsigned int
21 tokenize(const StringType& str,        
22         const StringType& delims,
23         Iter it,
24                 bool strip_whitespace=false)
25 {
26     typename StringType::size_type start_pos = 0;
27     typename StringType::size_type end_pos = 0;
28     unsigned int token_count = 0;
29
30     do {
31         start_pos = str.find_first_not_of(delims, start_pos);
32         end_pos = str.find_first_of(delims, start_pos);
33         if (start_pos != end_pos) {
34             if (end_pos == str.npos) {
35                 end_pos = str.length();
36             }
37                 if (strip_whitespace) {
38                                 StringType stripped = str.substr(start_pos, end_pos - start_pos);
39                                 strip_whitespace_edges (stripped);
40                                 if (stripped.length()) {
41                                         *it++ = stripped;
42                                 }
43                         } else {
44                 *it++ = str.substr(start_pos, end_pos - start_pos);
45                         }
46             ++token_count;
47             start_pos = str.find_first_not_of(delims, end_pos + 1);
48         }
49     } while (start_pos != str.npos);
50
51     if (start_pos != str.npos) {
52         if (strip_whitespace) {
53                         StringType stripped = str.substr(start_pos, str.length() - start_pos);
54                         strip_whitespace_edges (stripped);
55                         if (stripped.length()) {
56                                 *it++ = stripped;
57                         }
58                 } else {
59                 *it++ = str.substr(start_pos, str.length() - start_pos);
60                 }
61         ++token_count;
62     }
63
64     return token_count;
65 }
66
67 } // namespace PBD
68
69 #endif // PBD_TOKENIZER
70
71