C++中如何对字符串进行switch判断?

#include "stdafx.h" #include #include using namespace std; int main(int argc,argv[]) {string a="abcd"; string b; b=a.substr(0,1); switch (b) { case "a": cout<<"a!"; break; case "b": cout<<"b!"; break; } } 编译结果指着switch (b)这行出错,说switch expreation type of "std::string"

第1个回答  2019-12-13
你好!
语法上不支持.但我们可以变通.
比如把string
做一下hash处理,变成一个int数.
然后对这个int数进行switch.
这样子写的时候会复杂点.但是运行时快.比逐个字串比较要好
仅代表个人观点,不喜勿喷,谢谢。
相似回答
大家正在搜