1. Home
  2. Computing & Technology
  3. Delphi Programming

Case statement that *accepts* string values

By Zarko Gajic, About.com

You've probably tried providing a Case statement with string type selector expression, to find out that it only takes ordinal types (which string is not).

The following function enables you to use the Case statement with string type variables:

~~~~~~~~~~~~~~~~~~~~~~~~~
function StringToCaseSelect
   (Selector : string;
CaseList: array of string): Integer;
var cnt: integer;
begin
   Result:=-1;
   for cnt:=0 to Length(CaseList)-1 do
begin
     if CompareText(Selector, CaseList[cnt]) = 0 then
     begin
       Result:=cnt;
       Break;
     end;
   end;
end;

{
Usage:

case StringToCaseSelect('Delphi',
      ['About','Borland','Delphi']) of
   0:ShowMessage('You''ve picked About') ;
   1:ShowMessage('You''ve picked Borland') ;
   2:ShowMessage('You''ve picked Delphi') ;
end;
}

~~~~~~~~~~~~~~~~~~~~~~~~~

Delphi tips navigator:
» How to calculate the date of Easter for a given year
« Making an application restart with Windows

Zarko Gajic
Guide since 1998

Zarko Gajic
Delphi Programming Guide

Explore Delphi Programming
About.com Special Features

Stay connected and entertained with reviews on tips on the latest HDTVs, cellphones and more. More >

Easy ways to connect two computers for networking purposes. More >

  1. Home
  2. Computing & Technology
  3. Delphi Programming
  4. Coding Delphi Applications
  5. Delphi Tips and Tricks
  6. 2002 Delphi Tips
  7. Case statement that *accepts* string values

©2009 About.com, a part of The New York Times Company.

All rights reserved.