delphidelphi-xe2

Using Case Statement with String


Say i have a string

'SomeName'

and wanted the values return in a case statement. Can this bedone? Can strings be used in a case statement like so

Case 'SomeName' of

   'bobby' : 2;
   'tommy' :19;
   'somename' :4000;
else
   showmessage('Error');
end;

Solution

  • In Jcl library you have the StrIndex function StrIndex(Index, Array Of String) which works like this:

    Case StrIndex('SomeName', ['bobby', 'tommy', 'somename']) of 
      0: ..code.. ;//bobby
      1: ..code..;//tommy
      2: ..code..;//somename
    else
      ShowMessage('error');
    end.
    

    Delphi (independent of JCL) provides the same functionality through e.g.

    function IndexStr(const AText: string; const AValues: array of string): Integer;
    

    or

    function AnsiIndexStr(const AText: string; const AValues: array of string): Integer;