switch case判断字符串
时间: 2023-11-10 11:06:32 浏览: 36
在 C++ 中可以使用 switch case 结构判断一个字符串,但需要使用字符串哈希函数来将字符串转换为整数,并且需要在每个 case 中使用字符串比较函数判断是否相等。例如:
```
#include <iostream>
#include <string>
using namespace std;
unsigned int hash(const string& str) {
unsigned int hash_value = 0;
for (char ch : str) {
hash_value = hash_value * 31 + ch;
}
return hash_value;
}
int main() {
string input;
cin >> input;
switch (hash(input)) {
case hash("apple"):
cout << "你输入了苹果" << endl;
break;
case hash("banana"):
cout << "你输入了香蕉" << endl;
break;
case hash("orange"):
cout << "你输入了橙子" << endl;
break;
default:
cout << "你输入了其他水果" << endl;
break;
}
return 0;
}
```
请注意,使用字符串哈希函数来判断字符串相等有可能会出现哈希冲突,因此在实际应用中需要谨慎使用。