[Lazarus] Easiest way to "case" strings

Michael Van Canneyt michael at freepascal.org
Sat Mar 21 10:59:12 CET 2009



On Sat, 21 Mar 2009, Reenen Laurie wrote:

> Hi,
> 
> I'm sure most of you have had this... is there an easy way to have a case
> statement that's based on "strings" rather than ordinal types.  Is there
> somewhere a shortcut?
> 
> The only solution I can think of is defining constants with strings and
> ordinal types...
> 
> What I'd like to do is:
>    case fruit of:
>      'apple' :
>      'pear' :
>      'banana':
>      'grape':
>    else
> 
>    end;
> 
> So the only solution I can think of is
> const fruitlist = (apple,pear,banana,grape);
>            fruitstrings = ('apple','pear','banana','grape');
> 
> and then...
> 
> for i := apple to grape do
>   if fruit {string} = fruitstrings[i] then fruitvar := i;
> 
> case fruitvar of
>   apple :
>   pear :
>   banana :
>   grape :
> else
> end;
> 
> Any easier solutions to trying to run a case on a "string"?

Well, you could try this:

Program doit;

uses sysutils;

Function WordCase(Const S  : String; Const Options : Array of string) : Integer;

begin
  Result:=High(Options);
  While (Result>=0) and (COmpareText(S,Options[Result])<>0) do
    Dec(Result);
end;

begin
  Case WordCase(Paramstr(1),['zero','one','two','three']) of
    0 : Writeln('zero found');
    1 : Writeln('One found');
    2 : Writeln('Two found');
    3 : Writeln('Three found');
  else
    Writeln('Unknown case : ',paramstr(1));
  end;
end. 

It works for me :-)

Michael.



More information about the Lazarus mailing list