forked from snowie2000/mactype
-
Notifications
You must be signed in to change notification settings - Fork 0
/
strtoken.h
124 lines (112 loc) · 2.04 KB
/
strtoken.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
#pragma once
//例
// 'a,b,c,d' { "a", "b", "c", "d" }
// 'a,,b,c,' { "a", "", "b", "c", "" }
// '"a,b",c' { ""a,b"", "c" }
class CStringTokenizer
{
private:
enum _Const {
MAX_ARGUMENTS = 16,
};
int m_nNumArgs;
LPTSTR m_ppszArgv[MAX_ARGUMENTS + 1];
LPTSTR m_pszBuffer;
void Clear()
{
m_nNumArgs = 0;
ZeroMemory(m_ppszArgv, sizeof(m_ppszArgv));
free(m_pszBuffer);
m_pszBuffer = NULL;
}
public:
CStringTokenizer()
: m_pszBuffer(NULL)
{
Clear();
}
~CStringTokenizer()
{
free(m_pszBuffer);
}
int GetCount() const
{
return m_nNumArgs;
}
LPCTSTR GetArgument(int x) const
{
Assert(0 <= x && x <= GetCount());
return m_ppszArgv[x];
}
int Parse(LPCTSTR pszStr)
{
Clear();
if (!pszStr || !*pszStr) {
return 0;
}
m_pszBuffer = _tcsdup(pszStr);
if (!m_pszBuffer) {
return 0;
}
LPTSTR p = m_pszBuffer, ps;
int nNumArgs = 0;
LPTSTR* ppszArgv = m_ppszArgv;
#define _isspace(ch) (ch == _T('\t') || ch == _T(' '))
for (;;) {
CONT:
if (nNumArgs >= MAX_ARGUMENTS) {
TRACE(_T("Too many arguments (> %d)\n"), MAX_ARGUMENTS);
break;
}
if (*p == _T('\0')) {
ppszArgv[nNumArgs++] = p;
goto EXIT;
}
for (; _isspace(*p); *p++);
if (*p == _T('\0')) {
break;
}
switch (*p) {
case _T(','):
*p = _T('\0');
ppszArgv[nNumArgs++] = p++;
goto CONT;
case _T('"'):
p++;
ppszArgv[nNumArgs++] = p++;
for (; *p && *p != _T('"'); p++);
if (*p == _T('\0')) {
TRACE(_T("Unterminated string\n"));
goto EXIT;
}
*p++ = _T('\0');
break;
default:
ppszArgv[nNumArgs++] = p++;
ps = p;
for (; *p && *p != _T(','); p++);
if (*p == _T('\0')) {
goto EXIT;
}
for (p--; _isspace(*p) && p >= ps; p--);
p++;
break;
}
if (_isspace(*p)) {
for (*p++ = _T('\0'); *p && _isspace(*p); p++);
if (*p == _T('\0')) {
break;
}
}
for (; *p && *p != _T(','); p++);
if (*p == _T('\0')) {
break;
}
*p++ = _T('\0');
}
#undef _isspace
EXIT:
m_nNumArgs = nNumArgs;
return nNumArgs;
}
};