将字符串分成两半进行比较
Compare a string in two halves
我正在用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++中拆分字符串的更多信息。
相关文章:
- 视觉C++使用 map 来比较字符串中的每个单词
- 我正在尝试从输入文件中读取,然后使用它们的子字符串比较字符串的特定部分
- 比较字符串的 GetLine 工作一次,然后比较之后不起作用
- C++使用关系运算符比较字符串
- 通过默认复制构造函数比较 C++ 字符串是否会影响性能,原因为何?
- C++ TCP 服务器比较字符串失败
- 如何在不复制的情况下比较字符串的一部分?
- 比较 C++ 字符串打印中的两个整数数组
- 如何比较字符串形式的临时变量
- std::out_of_range 比较字符串中的符号时出错
- 比较字符串大小写不区分的简单方法是什么?
- 比较字符串忽略 NUL
- 比较字符串(arduino)时出现问题
- 如何在C++中比较字符串
- 比较字符串对象等于向量中的元素
- C 比较字符串操作速度
- 需要比较字符串的某些元素
- 比较字符串 .c_str() 和普通字符串的差异
- C 比较字符串的字符
- 通过使用两个不同的队列比较字符串