从cmdline解析出参数token

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
#include <string>
#include <vector>
#include <sstream>
 
using namespace std;
 
wstring copySpanStr(const wchar_t* start, const wchar_t* end)
{
	wchar_t* buf = (wchar_t*)malloc((end - start + 1) * sizeof(wchar_t));
	wchar_t* pTo = buf;
	for (const wchar_t* p = start; p != end; p++)
	{
		if (*p == L'\\' && p + 1 != end)
		{
			p++;
			*pTo++ = *p;
		}
		else
			*pTo++ = *p;
	}
	*pTo = 0;
	wstring out = buf;
	free(buf);
	return out;
}
 
int getParams(const wchar_t* str, vector<wstring>& out)
{
	int isInQMark = 0;
	int isInSpace = 1;
	const wchar_t* tokenStart = str;
	for (const wchar_t* p = str; ; p++)
	{
		if (*p == L'"')
		{
			if (!isInQMark)
			{
				isInQMark = 1;
				tokenStart = p + 1;
			}
			else
			{
				isInQMark = 0;
				out.push_back(copySpanStr(tokenStart, p));
			}
		}
		else if (*p == L'\\')
		{
			if (*(p + 1) != 0)
				p++;
		}
		else if (*p == L' ' || *p == 0)
		{
			if (!isInQMark)
			{
				if (!isInSpace)
				{
					isInSpace = 1;
					if (tokenStart != p)
					{
						out.push_back(copySpanStr(tokenStart, p));
						tokenStart = p;
					}
				}
				else
				{
 
				}
			}
		}
		else
		{
			if (!isInQMark)
			{
				if (!isInSpace)
				{
 
				}
				else
				{
					isInSpace = 0;
					tokenStart = p;
				}
			}
		}
		if (*p == 0)
			break;
	}
	return out.size();
}
 
wstring strReplaceCh2Str(const wchar_t* in, wchar_t fromCh, const wchar_t* toStr)
{
	const wchar_t* p = in;
	wstringstream ss;
	const wchar_t* pToStr;
	for (; *p != 0; p++)
	{
		if (*p == fromCh)
		{
			for (pToStr = toStr; *pToStr != 0; pToStr++)
			{
				ss << *pToStr;
			}
		}
		else
			ss << *p;
	}
	return ss.str();
}
 
int main()
{
	wstring path = strReplaceCh2Str(L"c:\\aa.txt", L'\\', L"\\\\");
	wstring msg = strReplaceCh2Str(L"\"优孩\"是EuhatExpert的中文名。", L'\"', L"\\\"");
 
	wstring cmd = L"EuhatExample.exe subCmd \"" + path + L"\" \"" + msg + L"\" 1234 5678";
 
	vector<wstring> params;
	getParams(cmd.c_str(), params);
	return 0;
}