其实这两个都差不多
[问题提出]
如何像vb那样在 CASE 语句中使用字符串? 在一大堆的字符串条件里跳转语句常被搞得晕头转向,太多的 IF ELSE 既花时间写,也花时间读。能不能用CASE语句来解决呢?
[解决]
Delphi中的 CASE 语句限制只能用顺序的(ordinal)类型,以至于不能在其中直接使用字符串。
解决它的根本思想是将字符串列转化成可比较的顺序类型。最简单的方法是将这些字符串作为一个字符串数组,它们在数组中的索引即代表它们各自的顺序。
[实现]
首先建立 CaseString 函数,用于获取某字符串在一个字符串数组中的顺序:
function CaseString (const s: string;
const x: array of string): Integer;
var i: Integer;
begin
Result:= -1; // Default return parameter
for i:= Low (x) to High (x) do begin
if s = x[i] then begin Result:= i; Exit; end;
end;
end;
Low() 提供第一个数组成员(通常是0),High() 则返回最后一个。因为 CaseString 返回的是待查字符串在字符串数组中的位置,因此,它可以被直接用到 CASE 语句中:
search:= 'delphi3000';
case CaseString (search, ['delphi3000',
'delphipages',
'Torry's']) of
0: s:= 'Excellent!';
1: s:= 'Good source';
2: s:= 'Not bad!';
end;
引用:http://www.52delphi.com/tips/delphi/opascal/26102301444.htm ;
function StringToCaseSelect
(Selector : string;
CaseList: array of string): Integer;
var cnt: integer;
begin
Result:=-1;
for cnt:=0 to Length(CaseList)-1 do
begin
if CompareText(Selector, CaseList[cnt]) = 0 then
begin
Result:=cnt;
Break;
end;
end;
end;
{
Usage:
case StringToCaseSelect('Delphi',
['About','Borland','Delphi']) of
0:ShowMessage('You''ve picked About') ;
1:ShowMessage('You''ve picked Borland') ;
2:ShowMessage('You''ve picked Delphi') ;
end;
}
引用:http://delphi.about.com/cs/adptips2002/a/bltip0202_5.htm