How to get the country name from the 2-letter country code (alpha-2) in Pascal

1 Answer

0 votes
program CountryLookup;

{$mode objfpc}{$H+}

uses
  SysUtils;

type
  {------------------------------------------------------------
   TCountryEntry
   Represents a single ISO alpha‑2 → country name mapping.
   ------------------------------------------------------------}
  TCountryEntry = record
    Code: string[2];
    Name: string;
  end;

{------------------------------------------------------------
  A sorted lookup table for fast binary search.
  Add more entries as needed, but keep it sorted by Code.
------------------------------------------------------------}
const
  CountryTable: array[0..8] of TCountryEntry = (
    (Code: 'CA'; Name: 'Canada'),
    (Code: 'CN'; Name: 'China'),
    (Code: 'DE'; Name: 'Germany'),
    (Code: 'FR'; Name: 'France'),
    (Code: 'GB'; Name: 'United Kingdom'),
    (Code: 'KR'; Name: 'South Korea'),
    (Code: 'IN'; Name: 'India'),
    (Code: 'JP'; Name: 'Japan'),
    (Code: 'US'; Name: 'United States')
  );

  CountryCount = Length(CountryTable);

{------------------------------------------------------------
  NormalizeCode
  Converts a 2‑letter code to uppercase for consistent matching.
------------------------------------------------------------}
function NormalizeCode(const S: string): string;
begin
  Result := UpperCase(Trim(S));
end;

{------------------------------------------------------------
  GetCountryName
  Performs a binary search on the sorted table.
  Returns an empty string if the code is not found.
------------------------------------------------------------}
function GetCountryName(const Alpha2: string): string;
var
  Code: string;
  Left, Right, Mid: Integer;
  Cmp: Integer;
begin
  Code := NormalizeCode(Alpha2);
  Left := 0;
  Right := CountryCount - 1;

  while Left <= Right do
  begin
    Mid := (Left + Right) div 2;
    Cmp := CompareStr(Code, CountryTable[Mid].Code);

    if Cmp = 0 then
    begin
      Result := CountryTable[Mid].Name;
      Exit;
    end
    else if Cmp < 0 then
      Right := Mid - 1
    else
      Left := Mid + 1;
  end;

  Result := '';  { Not found }
end;

{------------------------------------------------------------
  Main
  Demonstrates the lookup function with several sample codes.
------------------------------------------------------------}
var
  Codes: array[0..4] of string = ('US', 'GB', 'FR', 'JP', 'ZZ');
  I: Integer;
  Name: string;
begin
  for I := 0 to High(Codes) do
  begin
    Name := GetCountryName(Codes[I]);

    if Name <> '' then
      WriteLn(Codes[I], ' → ', Name)
    else
      WriteLn(Codes[I], ' → (invalid code)');
  end;
end.


{
run:

US → United States
GB → United Kingdom
FR → France
JP → Japan
ZZ → (invalid code)

}

 



answered Sep 19 by avibootz
...