]> git.saurik.com Git - wxWidgets.git/blob - src/common/tokenzr.cpp
95eb0d586072f8c5a10cf4741cd7abb0271e0304
[wxWidgets.git] / src / common / tokenzr.cpp
1 /////////////////////////////////////////////////////////////////////////////
2 // Name: tokenzr.cpp
3 // Purpose: String tokenizer
4 // Author: Guilhem Lavaux
5 // Modified by: Gregory Pietsch
6 // Created: 04/22/98
7 // RCS-ID: $Id$
8 // Copyright: (c) Guilhem Lavaux
9 // Licence: wxWindows licence
10 /////////////////////////////////////////////////////////////////////////////
11
12 #ifdef __GNUG__
13 #pragma implementation "tokenzr.h"
14 #endif
15
16 // For compilers that support precompilation, includes "wx.h".
17 #include "wx/wxprec.h"
18
19 #ifdef __BORLANDC__
20 #pragma hdrstop
21 #endif
22
23 #include "wx/tokenzr.h"
24
25 wxStringTokenizer::wxStringTokenizer(const wxString& to_tokenize,
26 const wxString& delims,
27 bool ret_delims)
28 {
29 m_string = to_tokenize;
30 m_delims = delims;
31 m_retdelims = ret_delims;
32 m_pos = 0;
33 }
34
35 wxStringTokenizer::~wxStringTokenizer()
36 {
37 }
38
39 int wxStringTokenizer::CountTokens() const
40 {
41 size_t pos = 0;
42 int count = 0;
43 bool at_delim;
44
45 while (pos < m_string.length()) {
46 // while we're still counting ...
47 at_delim = (m_delims.find(m_string.at(pos)) < m_delims.length());
48 // are we at a delimiter? if so, move to the next nondelimiter;
49 // if not, move to the next delimiter. If the find_first_of
50 // and find_first_not_of methods fail, pos will be assigned
51 // npos (0xFFFFFFFF) which will terminate the loop on the next
52 // go-round unless we have a really long string, which is unlikely
53 pos = at_delim ? m_string.find_first_not_of(m_delims, pos)
54 : m_string.find_first_of(m_delims, pos);
55 if (m_retdelims)
56 {
57 // if we're retaining delimiters, increment count
58 count++;
59 }
60 else
61 {
62 // if we're not retaining delimiters and at a token, inc count
63 count += (!at_delim);
64 }
65 }
66 return count;
67 }
68
69 bool wxStringTokenizer::HasMoreTokens()
70 {
71 return (m_retdelims
72 ? !m_string.IsEmpty()
73 : m_string.find_first_not_of(m_delims) < m_string.length());
74 }
75
76 wxString wxStringTokenizer::NextToken()
77 {
78 size_t pos;
79 wxString r_string;
80
81 if ( m_string.IsEmpty() )
82 return m_string;
83 pos = m_string.find_first_not_of(m_delims);
84 if ( m_retdelims ) {
85 // we're retaining delimiters (unusual behavior, IMHO)
86 if (pos == 0)
87 // first char is a non-delimiter
88 pos = m_string.find_first_of(m_delims);
89 } else {
90 // we're not retaining delimiters
91 m_string.erase(0, pos);
92 m_pos += pos;
93 if (m_string.IsEmpty())
94 return m_string;
95 pos = m_string.find_first_of(m_delims);
96 }
97 if (pos <= m_string.length()) {
98 r_string = m_string.substr(0, pos);
99 m_string.erase(0, pos);
100 m_pos += pos;
101 } else {
102 r_string = m_string;
103 m_pos += m_string.length();
104 m_string.Empty();
105 }
106 return r_string;
107 }