#pragma once
#include <set>
#include <map>
#include <string>
class CommandParser
{
public:
enum KEY_TYPE
{
SYMBOL_COLON, //:
SYMBOL_COMMA, //,
SYMBOL_LESS_THAN, //<
SYMBOL_GREATER_THAN, //>
SYMBOL_EQUAL_TO, //=
SYMBOL_LEFT_CURLY_BRACKETS, //{
SYMBOL_RIGHT_CURLY_BRACKETS, //}
SYMBOL_COUNT
};
CommandParser(const char* command);
const std::string& load();
bool isFinish();
private:
void initKey();
KEY_TYPE m_currentKey;
int m_index = 0;
std::string m_command;
std::string m_currentCommand;
static std::map<char, KEY_TYPE> g_keyMap;
};
#include "CommandParser.hpp"
#include <string>
std::map<char, CommandParser::KEY_TYPE> CommandParser::g_keyMap;
void CommandParser::initKey()
{
g_keyMap[':'] = SYMBOL_COLON;
g_keyMap[','] = SYMBOL_COMMA;
g_keyMap['<'] = SYMBOL_LESS_THAN;
g_keyMap['>'] = SYMBOL_GREATER_THAN;
g_keyMap['='] = SYMBOL_EQUAL_TO;
g_keyMap['{'] = SYMBOL_LEFT_CURLY_BRACKETS;
g_keyMap['}'] = SYMBOL_RIGHT_CURLY_BRACKETS;
}
CommandParser::CommandParser(const char* command)
{
m_command = command;
m_currentKey = SYMBOL_COUNT;
if (g_keyMap.empty())
{
initKey();
}
}
bool CommandParser::isFinish()
{
//while结束的条件
return m_index >= m_command.size();
}
const std::string& CommandParser::load()
{
m_currentCommand = "";
m_currentKey = SYMBOL_COUNT;
while (!isFinish())
{
char c = m_command[m_index++];
std::map<char, CommandParser::KEY_TYPE>::iterator it = g_keyMap.find(c);
if (it == g_keyMap.end())
{
m_currentCommand.push_back(c);
}
else
{
m_currentKey = it->second;
break;
}
}
return m_currentCommand;
}
main中调用
int main(int argc, char ** argv)
{
CommandParser c1("load:battle_server_0.bin");
while (!c1.isFinish())
{
printf("%s", c1.load().c_str());
}
return 0;
}
打印结果(:被剔除掉了)