首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何解析具有多种可能性的字符串?

如何解析具有多种可能性的字符串?
EN

Stack Overflow用户
提问于 2014-11-16 05:28:09
回答 1查看 75关注 0票数 0

我最近写了很多重复的代码。我需要想出一个更好的解决方案。

至于现在我正在做这件事(伪代码)

代码语言:javascript
复制
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
}

但每个SomeParsingCode*代码片段都包含许多重复的代码,如IsValidPlayer(string)//returns Cplayer from id or name,将字符串解析为数字或浮点数或其他任何内容。

我正在考虑通过创建一个通用的解析函数来简化代码的编写,比如:

auto result = ParseMyParameters("Player_string_or_int;int_or_hex;int_or_hex",input) if(result.good()){ //continue

我在考虑将每个请求映射到一个字符,如下所示:

代码语言:javascript
复制
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"

然后创建一个函数,循环一个字符串,逐个解析所有请求的内容。

但是我在想,C++有这么多好东西,我真的不知道在这种情况下应该使用什么,我可以使用哪些容器或boost/C++来完成这项任务?在C++中有没有什么东西可以让我来做呢?推荐使用哪种方法?

此外,这可能需要一些可变参数,使用varargs或我可以使用一些可变模板?喜欢

ParseString<cplayer*,int,float,std::string>("Joe 5 5.0 hello my friend!");

使用

std::string = "hello my friend!";

ParseString<cplayer*,int,float,std::vector<std::string>>("Joe 5 5.0 hello my friend!");

使用std::vector<std::string> = {"hello", "my", "friend!"};

EN

回答 1

Stack Overflow用户

发布于 2014-11-16 05:36:42

使用LEX (FLEX)或YACC (BISON)做这类事情要容易得多。

您可以使用它们来定义命令,并在遇到命令时提供操作。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/26950918

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档