C语言switch并不支持字符串,但对于长度小于等于4个的短字符串,单引号可以将其转为int类型,如int a = 'abcd';是合理的,其在内存中的是连续存储的4个字节,可以转换为int。

对于长度大于4的字符串,单引号只能将最后4个字符转为int,应该与机器的位数和大小端模式有关。

因此,对于长度小于4的字符串,使用switch的方式为

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
int to_int(char *str)
{
int res = 0;
for (int i = 0; i < strlen(str); i++)
{
res <<= 8;
res |= str[i];
}
return res;
}

void switch_str(char *str)
{
switch (to_int(str))
{
case 'abc':
break;

case '1234':
break;

case 'xx':
break;
}
}