How to find the country code by the country name in C

1 Answer

0 votes
#include <stdio.h>
#include <string.h>
#include <ctype.h>

// -------------------------------------------------------------
// normalizeCountryName
// Converts "france", "FRANCE", "fRaNcE" → "France"
// Converts "united states" → "United States"
// This matches the format used in the map keys.
// -------------------------------------------------------------
void normalizeCountryName(char *s) {
    int i;

    // Convert entire string to lowercase first
    for (i = 0; s[i]; i++) {
        s[i] = tolower((unsigned char)s[i]);
    }

    // Capitalize the first letter of each word
    int capitalizeNext = 1;
    for (i = 0; s[i]; i++) {
        if (capitalizeNext && isalpha((unsigned char)s[i])) {
            s[i] = toupper((unsigned char)s[i]);
            capitalizeNext = 0;
        } else if (s[i] == ' ') {
            capitalizeNext = 1;
        }
    }
}

// -------------------------------------------------------------
// getCountryCode
// Works with lowercase, uppercase, mixed-case input.
// Map stays exactly as you defined it.
// -------------------------------------------------------------
const char* getCountryCode(const char *countryName) {
    // Copy input because we need to modify it
    static char key[128];
    strncpy(key, countryName, sizeof(key));
    key[sizeof(key)-1] = '\0';

    // Normalize input to match map keys
    normalizeCountryName(key);

    // Lookup table stored exactly as given
    static const struct {
        const char *name;
        const char *code;
    } countryCodes[] = {
        {"United States", "US"},
        {"Canada", "CA"},
        {"United Kingdom", "GB"},
        {"France", "FR"},
        {"Germany", "DE"},
        {"Romania", "RO"},
        {"Japan", "JP"},
        {"Australia", "AU"},
        {"Hungary", "HU"}
    };

    // Search the array
    int len = (int)(sizeof(countryCodes)/sizeof(countryCodes[0]));
    for (int i = 0; i < len; i++) {
        if (strcmp(key, countryCodes[i].name) == 0) {
            return countryCodes[i].code;
        }
    }

    return "Unknown";
}

int main() {
    char name[128] = "";

    printf("Enter a country name: ");
    fgets(name, sizeof(name), stdin);

    // Remove trailing newline
    name[strcspn(name, "\n")] = '\0';

    const char *code = getCountryCode(name);

    printf("Country code: %s\n", code);

    return 0;
}



/*
run:

Enter a country name: Romania
Country code: RO


Enter a country name: romania
Country code: RO

*/

 



answered 5 days ago by avibootz

Related questions

...