C++ 如何解析具有多种可能性的字符串?
我最近写了很多重复的代码。我需要想出一个更好的解决办法 现在我正在做这个伪代码C++ 如何解析具有多种可能性的字符串?,c++,parsing,C++,Parsing,我最近写了很多重复的代码。我需要想出一个更好的解决办法 现在我正在做这个伪代码 std::map<std::string/*commandname*/, commandfunction*> Commands; void OnPlayerExecuteCommand(cplayer* player, std::string command, std::string parameters) { //find check blablabla yaddayadda then..
std::map<std::string/*commandname*/, commandfunction*> Commands;
void OnPlayerExecuteCommand(cplayer* player, std::string command, std::string parameters)
{
//find check blablabla yaddayadda then..
Commands[command]->execute(player, parameters);
}
//heal PlayerId/Name (float)amount
void Command_HealMe(cplayer* player, std::string parameters)
{
SomeParsingCodeA(params);//get the cplayer* from playername or id and float heal amount
}
//vehicle name color1 color2, eg /vehicle Ferrari 0xFF0000 123456
void Command_SpawnVehicle(cplayer* player, std::string parameters)
{
SomeParsingCodeB(params);//get the vehiclename, and colors
}
//kick playername/id reason, eg /kick player_a you are spamming the chat
void Command_KickSomeone(cplayer* player, std::string parameters)
{
SomeParsingCodeC(params);//get cplayer* of playername or id, and get the rest string
}
然后生成一个函数,该函数循环一个字符串并逐个解析所有请求的内容
但是我一直在想C++有很多好东西,我真的不知道在这个情况下该怎么用,容器或Boosiv/C++包含了什么?C++中有什么东西让我这么做了吗?建议采用什么方法
此外,这可能需要一些可变参数,使用varargs,或者我可以使用一些可变模板吗?像
ParseStringJoe5.0你好,我的朋友
与
std::string=你好,我的朋友
或
ParseStringJoe5.0你好,我的朋友
用std::vector={你好,我的朋友!}
?使用LEX FLEX或YACC BISON,这类事情要容易得多 您可以使用它们定义命令,并在遇到命令时提供操作
character - expected input
u - PlayerName as String or PlayerID as integer(u as in user)
i - integer number
x - hex formatted number
f - real number
g - integer or hex
w - one worded string
r - return remaining string,
like /kick player_a you are spamming the chat
would be parsed with "ur", and the result would be a cplayer pointer and the string "you are spamming the chat"