c語(yǔ)言swtich能處理字符串嗎

小樊
81
2024-10-16 22:33:26

在C語(yǔ)言中,switch語(yǔ)句本身不能直接處理字符串。switch語(yǔ)句主要用于處理整數(shù)類型的值。

然而,你可以使用字符串指針和strcmp函數(shù)來(lái)實(shí)現(xiàn)類似于處理字符串的功能。以下是一個(gè)示例:

#include <stdio.h>
#include <string.h>

int main() {
    char *str1 = "hello";
    char *str2 = "world";

    char input[100];
    printf("Enter a string: ");
    fgets(input, sizeof(input), stdin);

    // 去掉換行符
    input[strcspn(input, "\n")] = 0;

    switch (strcmp(input, str1)) {
        case 0:
            printf("You entered: %s\n", str1);
            break;
        case 1:
            printf("You entered: %s (but it's not equal to %s)\n", input, str1);
            break;
        default:
            printf("You entered a different string: %s\n", input);
            break;
    }

    return 0;
}

在這個(gè)示例中,我們使用strcmp函數(shù)比較用戶輸入的字符串和預(yù)定義的字符串(如"hello")。strcmp函數(shù)返回一個(gè)整數(shù),如果兩個(gè)字符串相等,則返回0;如果第一個(gè)字符串在字典順序上位于第二個(gè)字符串之前,則返回一個(gè)負(fù)數(shù);否則,返回一個(gè)正數(shù)。然后,我們使用switch語(yǔ)句根據(jù)strcmp函數(shù)的返回值執(zhí)行不同的操作。

請(qǐng)注意,這種方法并不是直接使用switch處理字符串,而是通過(guò)比較字符串的哈希值(實(shí)際上是由strcmp函數(shù)完成的)來(lái)實(shí)現(xiàn)類似的功能。

0