📜  C |运营商|问题8(1)

📅  最后修改于: 2023-12-03 15:13:47.702000             🧑  作者: Mango

C | 运营商问题8
问题描述

设计一个程序,根据给定的手机号码,判断该号码属于哪家运营商。

输入

一个长度为11位的数字字符串,表示手机号码。

输出

一个字符串,表示该手机号码的运营商名称。

运营商列表

以下是几家常见的运营商及其号段:

  • 移动:138, 139, 136, 137, 150, 151, 152, 157, 158, 159, 182, 183, 184, 187, 188, 147, 178, 1705
  • 联通:130, 131, 132, 155, 156, 185, 186, 145, 176, 1709
  • 电信:133, 153, 180, 181, 189, 177, 1700
示例

输入:

"13812345678"

输出:

"移动"
解题思路

我们可以根据手机号码的前几位数字进行匹配,判断其属于哪个运营商。

代码实现

下面是一个简单的 C 代码示例实现:

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

const char* getOperator(const char* phoneNumber) {
    // 移动
    if (strncmp(phoneNumber, "138", 3) == 0 ||
        strncmp(phoneNumber, "139", 3) == 0 ||
        strncmp(phoneNumber, "136", 3) == 0 ||
        strncmp(phoneNumber, "137", 3) == 0 ||
        strncmp(phoneNumber, "150", 3) == 0 ||
        strncmp(phoneNumber, "151", 3) == 0 ||
        strncmp(phoneNumber, "152", 3) == 0 ||
        strncmp(phoneNumber, "157", 3) == 0 ||
        strncmp(phoneNumber, "158", 3) == 0 ||
        strncmp(phoneNumber, "159", 3) == 0 ||
        strncmp(phoneNumber, "182", 3) == 0 ||
        strncmp(phoneNumber, "183", 3) == 0 ||
        strncmp(phoneNumber, "184", 3) == 0 ||
        strncmp(phoneNumber, "187", 3) == 0 ||
        strncmp(phoneNumber, "188", 3) == 0 ||
        strncmp(phoneNumber, "147", 3) == 0 ||
        strncmp(phoneNumber, "178", 3) == 0 ||
        strncmp(phoneNumber, "1705", 4) == 0)
    {
        return "移动";
    }
    // 联通
    else if (strncmp(phoneNumber, "130", 3) == 0 ||
             strncmp(phoneNumber, "131", 3) == 0 ||
             strncmp(phoneNumber, "132", 3) == 0 ||
             strncmp(phoneNumber, "155", 3) == 0 ||
             strncmp(phoneNumber, "156", 3) == 0 ||
             strncmp(phoneNumber, "185", 3) == 0 ||
             strncmp(phoneNumber, "186", 3) == 0 ||
             strncmp(phoneNumber, "145", 3) == 0 ||
             strncmp(phoneNumber, "176", 3) == 0 ||
             strncmp(phoneNumber, "1709", 4) == 0)
    {
        return "联通";
    }
    // 电信
    else if (strncmp(phoneNumber, "133", 3) == 0 ||
             strncmp(phoneNumber, "153", 3) == 0 ||
             strncmp(phoneNumber, "180", 3) == 0 ||
             strncmp(phoneNumber, "181", 3) == 0 ||
             strncmp(phoneNumber, "189", 3) == 0 ||
             strncmp(phoneNumber, "177", 3) == 0 ||
             strncmp(phoneNumber, "1700", 4) == 0)
    {
        return "电信";
    }
    else {
        return "未知运营商";
    }
}

int main() {
    const char* phoneNumber = "13812345678";
    const char* operator = getOperator(phoneNumber);
    printf("%s\n", operator);
    return 0;
}

以上代码通过比较手机号码的前几位数字,来判断其属于哪个运营商,并返回对应的运营商名称。

注意:此示例代码仅给出了一种实现思路,实际运营商号段可能会发生变化,具体实现需要根据实际情况进行调整。