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; 16 Answers
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. 3The Delphi Case Statement only supports ordinal types. So you cannot use strings directly.
But exist another options like
- build a function which returns a Integer (hash) based on a string
- using generics and anonymous methods ( A generic case for strings)
- using a function which receive an array of strings (Making a case for Strings, the sane way)
- and so on.
@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.
2Works on D7 and Delphi Seattle,
uses StrUtils (D7) system.Ansistring (Delphi Seattle) system.StrUtils (Berlin 10.1) case AnsiIndexStr(tipo, ['E','R'] ) of 0: result := 'yes'; 1: result := 'no'; end; I used AnsiStringIndex and works, but if you can convert to number without problems:
try number := StrToInt(yourstring); except number := 0; end; 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;