c++中string字符串中switch case的用法
时间: 2023-04-29 09:06:17 浏览: 100
在C++中,可以使用switch case语句来对字符串进行判断。首先需要将字符串转换为整数类型,可以使用以下方式:
1. 使用哈希表将字符串映射到整数,再使用switch语句判断整数值。
2. 使用库函数strcmp()将字符串与每个case语句的字符串进行比较,匹配成功则执行相应的语句。
例如:
```c++
string str = "apple";
int hashValue = hashFunc(str); // 假设使用哈希表映射为整数
switch (hashValue) {
case 1:
// do something
break;
case 2:
// do something
break;
default:
// do something
break;
}
```
或者:
```c++
string str = "apple";
switch (strcmp(str.c_str(), "apple")) {
case 0:
// do something
break;
case 1:
// do something
break;
default:
// do something
break;
}
```
相关问题
c++中使用字符串hash函数加switch
在C++中使用字符串hash函数加switch可以实现快速的字符串匹配,可以避免使用if-else语句进行逐个比对,从而提高程序的效率。具体实现步骤如下:
1. 定义字符串hash函数,将字符串转化为一个整数,可以使用STL中的hash函数或自己实现一个hash函数。
2. 在switch语句中使用hash值进行匹配,每个case语句匹配一个特定的hash值,从而实现字符串的匹配。
示例代码如下:
```c++
#include <iostream>
#include <string>
#include <functional>
using namespace std;
// 定义字符串hash函数
struct StrHash {
size_t operator()(const string& str) const {
return hash<string>()(str);
}
};
int main() {
unordered_map<size_t, string> map = {
{hash<string>()("hello"), "Hello World!"},
{hash<string>()("world"), "World Hello!"},
{hash<string>()("good"), "Good Morning!"},
{hash<string>()("night"), "Good Night!"}
};
string str;
cout << "Please enter a string: ";
getline(cin, str);
// 使用字符串hash值进行匹配
switch (hash<string>()(str)) {
case hash<string>()("hello"):
cout << map[hash<string>()("hello")] << endl;
break;
case hash<string>()("world"):
cout << map[hash<string>()("world")] << endl;
break;
case hash<string>()("good"):
cout << map[hash<string>()("good")] << endl;
break;
case hash<string>()("night"):
cout << map[hash<string>()("night")] << endl;
break;
default:
cout << "Unknown input!" << endl;
break;
}
return 0;
}
```
注意:使用字符串hash函数加switch时,需要保证hash函数的唯一性,否则可能会出现hash冲突,导致匹配错误。
switch case 字符串
在 C++ 11 之后,支持使用字符串作为 switch case 条件。具体实现方式可以使用 std::string 或者 char[] 类型来表示字符串,然后使用常量表达式来作为 case 条件。下面是一个示例代码:
```
#include <iostream>
#include <string>
using namespace std;
int main() {
string str = "hello";
switch (str[0]) {
case 'h':
cout << "The first letter is h" << endl;
break;
case 'w':
cout << "The first letter is w" << endl;
break;
default:
cout << "The first letter is neither h nor w" << endl;
}
return 0;
}
```
在上面的代码中,我们使用 std::string 类型表示字符串,并且使用 str[0] 来获取字符串的第一个字符。然后我们使用 switch case 来判断第一个字符是不是 'h' 或者 'w'。如果是,就输出对应的信息,否则输出默认信息。