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

1 Answer

0 votes
program CountryCodeLookup;

{$mode objfpc}{$H+}


// -------------------------------------------------------------
// normalizeCountryName
// Converts "france", "FRANCE", "fRaNcE" → "France"
// Converts "united states" → "United States"
// This matches the format used in the map keys.
// -------------------------------------------------------------
procedure NormalizeCountryName(var S: string);
var
  i: Integer;
  CapitalizeNext: Boolean;
begin
  // Convert entire string to lowercase first
  S := LowerCase(S);

  // Capitalize the first letter of each word
  CapitalizeNext := True;
  for i := 1 to Length(S) do
  begin
    if CapitalizeNext and (S[i] in ['a'..'z']) then
    begin
      S[i] := UpCase(S[i]);
      CapitalizeNext := False;
    end
    else if S[i] = ' ' then
      CapitalizeNext := True;
  end;
end;

// -------------------------------------------------------------
// getCountryCode
// Works with lowercase, uppercase, mixed-case input.
// Map stays exactly as you defined it.
// -------------------------------------------------------------
function GetCountryCode(const CountryName: string): string;
type
  TCountryEntry = record
    Name: string;
    Code: string;
  end;
const
  CountryCodes: array[0..8] of TCountryEntry = (
    (Name: 'United States'; Code: 'US'),
    (Name: 'Canada'; Code: 'CA'),
    (Name: 'United Kingdom'; Code: 'GB'),
    (Name: 'France'; Code: 'FR'),
    (Name: 'Germany'; Code: 'DE'),
    (Name: 'Romania'; Code: 'RO'),
    (Name: 'Japan'; Code: 'JP'),
    (Name: 'Australia'; Code: 'AU'),
    (Name: 'Hungary'; Code: 'HU')
  );
var
  Key: string;
  i: Integer;
begin
  // Copy input because we need to modify it
  Key := CountryName;

  // Normalize input to match map keys
  NormalizeCountryName(Key);

  // Search the array
  for i := Low(CountryCodes) to High(CountryCodes) do
  begin
    if Key = CountryCodes[i].Name then
      Exit(CountryCodes[i].Code);
  end;

  Result := 'Unknown';
end;

var
  Name: string;
  Code: string;

begin
  Write('Enter a country name: ');
  ReadLn(Name);

  Code := GetCountryCode(Name);

  WriteLn('Country code: ', Code);
end.



(*
run:

Enter a country name: Hungary
Country code: HU

*)

 



answered Jun 17 by avibootz

Related questions

...