delphi的case语法当中能不能使用字符串?。
下面语句在delphi7和delphi2007同样报错不知可不可以?。 str:string; case str of
'a': showmessage('a');
'b': showmessage('b');
'c': showmessage('c');
end;
下面语句在delphi7和delphi2007同样报错不知可不可以?。 str:string; case str of
'a': showmessage('a');
'b': showmessage('b');
'c': showmessage('c');
end;
object Pascal这样规定的
case of 语句的选择器表达式是
任何有序类型的表达式.
A numeral, declared constant, or other expression that the compiler can evaluate without executing your program. It must be of an ordinal type compatible with selectorExpression. Thus 7, True, 4 + 5 * 3, 'A', and Integer('A') can all be used as caseLists, but variables and most function calls cannot. (A few built-in functions like Hi and Lo can occur in a caseList. See Constant expressions.)
A subrange having the form First..Last, where First and Last both satisfy the criterion above and First is less than or equal to Last.
A list having the form item1, ..., itemn, where each item satisfies one of the criteria above.
1)
if str<>'' then
case str[1] of
'a': showmessage('a');
'b': showmessage('b');
'c': showmessage('c');
end;2)
自己定义一个hash函数:
function hash(str:string):integer; case hash(str) of
hash('a'):
hash('b'):
hash('c'):
end;
只能先计算好hash的值手工填写进去
begin
str := str + ' ';
Result := ord(str[1]) SHL 24+ord(str[2]) SHL 16+ord(str[3]) SHL 8 + ord(str[4]);
//最简单的hash函数,取str前4个字符
end; case hash(str) of
1234: //这儿需要预先算出'a'的hash值
1235:
1236:
end;
不过这太麻烦了,不要考虑这种方法。还可以用下面这种方法:
function getStrIndex(s:string; a :array of string):integer;
var
i:integer;
begin
result := -1;
for i:= 0 to high(a) do
if lowercase(a[i]) = lowercase(s) then
begin
result := i;
exit;
end;
end; case getStrIndex(str, ['a','b','c']) of
0:
1:
2:
else;
这是比较好的方法了。
http://blog.csdn.net/lee576/archive/2007/11/30/1908427.aspx
看看吧