使用带有字符串的 Case 语句

问题描述 投票:0回答:6

假设我有一根绳子

'SomeName'

并希望在 case 语句中返回值。这可以吗?字符串可以像这样在 case 语句中使用吗

Case 'SomeName' of

   'bobby' : 2;
   'tommy' :19;
   'somename' :4000;
else
   showmessage('Error');
end;
delphi delphi-xe2
6个回答
43
投票

在 Jcl 库中,您有 StrIndex 函数

StrIndex(Index, Array Of String)
,其工作原理如下:

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

41
投票

Delphi

Case Statement
仅支持序数类型。所以不能直接使用字符串。

但是还存在其他选项,例如


21
投票

@Daniel 的回答为我指明了正确的方向,但我花了一段时间才注意到“Jcl Library”部分和有关标准版本的评论。

在[至少] 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 版本,分别使用

AnsiIndexStr
AnsiIndexText

感谢@Daniel、@The_Fox 和@afrazier 对于这个答案的大部分内容。


5
投票

适用于 D7 和德尔福西雅图,

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;

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;
© www.soinside.com 2019 - 2024. All rights reserved.