35
votes

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;
5
It seems that FreePascal (FPC) already implemented this language feature, I wish Delphi will follow up! [forum.lazarus.freepascal.org/index.php?topic=17983.0] - Edwin Yip

5 Answers

38
votes

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.
34
votes

The Delphi Case Statement only supports ordinal types. So you cannot use strings directly.

But exist another options like

18
votes

@Daniel's answer pointed me in the right direction, but it took me a while to notice the "Jcl Library" part and the comments about the standard versions.

In [at least] XE2 and later, you can use:

Case IndexStr('somename', ['bobby', 'tommy', 'somename', 'george']) of 
  0: ..code..;                   // bobby
  1: ..code..;                   // tommy
  2: ..code..;                   // somename
 -1: ShowMessage('Not Present'); // not present in array
else
  ShowMessage('Default Option'); // present, but not handled above
end;

This version is case-sensitive, so if the first argument was 'SomeName' it would take the not present in array path. Use IndexText for case-insensitive comparison.

For older Delphi versions, use AnsiIndexStr or AnsiIndexText, respectively.

Kudos to @Daniel, @The_Fox, and @afrazier for most of the components of this answer.

4
votes

Works on D7 and Delphi Seattle,

uses StrUtils (D7) system.Ansistring (Delphi Seattle)

case AnsiIndexStr(tipo, ['E','R'] )   of
      0: result := 'yes';
      1: result := 'no';
end;
0
votes

I used AnsiStringIndex and works, but if you can convert to number without problems:

try
  number := StrToInt(yourstring);
except
  number := 0;
end;