在使用字符串的情况下使用Case语句

39

假设我有一个字符串

'SomeName'

我想让值在case语句中返回。这可行吗?可以像这样在case语句中使用字符串吗?

Case 'SomeName' of

   'bobby' : 2;
   'tommy' :19;
   'somename' :4000;
else
   showmessage('Error');
end;

3
似乎FreePascal(FPC)已经实现了这个语言特性,我希望Delphi能够跟上![http://forum.lazarus.freepascal.org/index.php?topic=17983.0] - Edwin Yip
6个回答

43

Jcl库中有一个StrIndex函数StrIndex(Index,ArrayOfString),其工作方式如下:

Case StrIndex('SomeName', ['bobby', 'tommy', 'somename']) of 
  0: ..code.. ;//bobby
  1: ..code..;//tommy
  2: ..code..;//somename
else
  ShowMessage('error');
end.

13
可以使用标准的 AnsiIndexStr 函数。 - The_Fox
20
在更近的 Delphi 版本中,你可以使用 IndexStr。如果你需要进行不区分大小写的比较,也可以使用 -Text 版本。 - afrazier
我猜应该是end;而不是end.吧? - undefined

41

21

@Daniel的答案给了我正确的方向,但花了我一些时间才注意到“Jcl库”部分以及有关标准版本的注释。

在[XE2至少]及以后的版本中,您可以使用:

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;

这个版本是区分大小写的,所以如果第一个参数是“SomeName”,它将采用not present in array路径。使用IndexText进行不区分大小写的比较。

对于旧版 Delphi,请分别使用 AnsiIndexStrAnsiIndexText

感谢 @Daniel、@The_Fox 和 @afrazier 对本答案大部分组件的贡献。


1
IndexStr和AnsiIndexStr在Delphi 2007中也可以使用。单位StrUtils。 - Radek Secka

5

能在D7和Delphi Seattle上工作,

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

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

0

我使用了 AnsiStringIndex 并且可以工作,但如果您能够无误地将其转换为数字:

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

-1

试试这个,它使用了 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;

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接