Using Case Statement with String
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'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.
The 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.