1 // (C) Copyright Jeremy Siek 2004
2 // Distributed under the Boost Software License, Version 1.0. (See
3 // accompanying file LICENSE_1_0.txt or copy at
4 // http://www.boost.org/LICENSE_1_0.txt)
6 #ifndef BOOST_STRINGTOK_HPP
7 #define BOOST_STRINGTOK_HPP
10 * stringtok.hpp -- Breaks a string into tokens. This is an example for lib3.
12 * Template function looks like this:
14 * template <typename Container>
15 * void stringtok (Container &l,
17 * char const * const ws = " \t\n");
19 * A nondestructive version of strtok() that handles its own memory and can
20 * be broken up by any character(s). Does all the work at once rather than
21 * in an invocation loop like strtok() requires.
23 * Container is any type that supports push_back(a_string), although using
24 * list<string> and deque<string> are indicated due to their O(1) push_back.
25 * (I prefer deque<> because op[]/at() is available as well.) The first
26 * parameter references an existing Container.
28 * s is the string to be tokenized. From the parameter declaration, it can
29 * be seen that s is not affected. Since references-to-const may refer to
30 * temporaries, you could use stringtok(some_container, readline("")) when
31 * using the GNU readline library.
33 * The final parameter is an array of characters that serve as whitespace.
34 * Whitespace characters default to one or more of tab, space, and newline,
37 * 'l' need not be empty on entry. On return, 'l' will have the token
43 * stringtok (ls, " this \t is\t\n a test ");
44 * for (list<string>::const_iterator i = ls.begin();
47 * cerr << ':' << (*i) << ":\n";
57 * pedwards@jaj.com May 1999
62 #include <cstring> // for strchr
65 /*****************************************************************
66 * This is the only part of the implementation that I don't like.
67 * It can probably be improved upon by the reader...
71 isws (char c
, char const * const wstr
)
74 return (strchr(wstr
,c
) != NULL
);
80 /*****************************************************************
81 * Simplistic and quite Standard, but a bit slow. This should be
82 * templatized on basic_string instead, or on a more generic StringT
83 * that just happens to support ::size_type, .substr(), and so on.
84 * I had hoped that "whitespace" would be a trait, but it isn't, so
85 * the user must supply it. Enh, this lets them break up strings on
86 * different things easier than traits would anyhow.
88 template <typename Container
>
90 stringtok (Container
&l
, std::string
const &s
, char const * const ws
= " \t\n")
92 typedef std::string::size_type size_type
;
93 const size_type S
= s
.size();
97 // eat leading whitespace
98 while ((i
< S
) && (isws(s
[i
],ws
))) ++i
;
99 if (i
== S
) return; // nothing left but WS
103 while ((j
< S
) && (!isws(s
[j
],ws
))) ++j
;
106 l
.push_back(s
.substr(i
,j
-i
));
108 // set up for next loop
116 #endif // BOOST_STRINGTOK_HPP