将字符串分成两半进行比较

Compare a string in two halves

本文关键字:比较 字符串      更新时间:2023-10-16

我正在用C++构建一个基于文本的游戏,作为我学习的副项目,所以我试图找到一种方法,让字符串分两半进行评估。它将检查第一个单词,然后如果该单词被识别,它将看到它后面的单词是什么。例如,如果 getln() 中的输入;是"拿苹果"它会识别"拿",然后检查你在字符串的后半部分到底在拿什么。现在我能想到的唯一方法是玩家输入"take",这会导致大量嵌套的 if/else 语句。

您可以尝试将输入字符串标记化为其组件。然后,鉴于您使用C++,我建议使用多态的无条件设计:

创建基本类型:

class Command {
  public:
    virtual void exec(::std::vector<::std::string> parameters) = 0;
};

然后创建子命令,例如:

class TakeCommand : public Command {
  public:
    virtual void exec(::std::vector<::std::string> parameters);
};

然后,在启动期间,构建自己,一个字典(或Trie,如果你觉得花花公子的话)

::std::map<::std::string,::std::shared_ptr<Command>> commandProcessor;

由于这是一个地图,您可以检查该命令是否存在:

auto const it = commandProcessor.find(tokens[0]);
if (it != commandProcessor.end())
  it->second->exec(tokens);
  // you might want to strip the first token from the vector first!

任何您不熟悉的类型/功能,都可以在 http://en.cppreference.com/w/查找

我要做的是从用户那里获取输入,然后使用" "作为分量仪拆分字符串。 您仍然有一个嵌套的 if 语句,但它将消除用户输入两次的需要。

请参阅这篇文章以了解有关在C++中拆分字符串的更多信息。