39

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;
Glen Morse
  • 2,437
  • 8
  • 51
  • 102
  • 3
    It seems that FreePascal (FPC) already implemented this language feature, I wish Delphi will follow up! [http://forum.lazarus.freepascal.org/index.php?topic=17983.0] – Edwin Yip May 14 '14 at 07:30

6 Answers6

43

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.
Daniel
  • 1,052
  • 9
  • 11
41

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

But exist another options like

RRUZ
  • 134,889
  • 20
  • 356
  • 483
21

@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.

c32hedge
  • 785
  • 10
  • 19
5

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;
keno
  • 51
  • 1
  • 3
0

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

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

try this it uses System.StrUtils

procedure TForm3.Button1Click(Sender: TObject);
const
  cCaseStrings : array [0..4] of String = ('zero', 'one', 'two', 'three', 'four');
var
  LCaseKey : String;
begin
  LCaseKey := 'one';
  case IndexStr(LCaseKey, cCaseStrings) of
    0: ShowMessage('0');
    1: ShowMessage('1');
    2: ShowMessage('2');
    else ShowMessage('-1');
  end;
end;
NEQSH
  • 1
  • 1