delphi的case语法当中能不能使用字符串?。
下面语句在delphi7和delphi2007同样报错不知可不可以?。 str:string; case str of
   'a': showmessage('a');
   'b': showmessage('b');
   'c': showmessage('c');
 end;

解决方案 »

  1.   

    不能使用字符串.
    object Pascal这样规定的
    case of 语句的选择器表达式是
    任何有序类型的表达式.
      

  2.   

    delphi中case不能用字符,必须是有序的
      

  3.   

    where selectorExpression is any expression of an ordinal type smaller than 32 bits (string types and ordinals larger than 32 bits are invalid) and each caseList is one of the following:
     
    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. 
      

  4.   

    OP语法不支持String在Case中使用
      

  5.   

    delphi不支持在case中直接使用string,但是可以变通:
    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;
      

  6.   

    不好意思,方法2不能运行,case语句中不能使用变量
    只能先计算好hash的值手工填写进去
      

  7.   

    function   hash(str:string):integer; 
    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;
    这是比较好的方法了。
      

  8.   

    用字符的字符编码,case ord(str[1])) of 65..90
      

  9.   

    记得01年还是02年的程序员杂志提到过case中字符串的问题,基本上跟windindance说的一样.
      

  10.   

    在 case 语句中使用字符串  
    http://blog.csdn.net/lee576/archive/2007/11/30/1908427.aspx
    看看吧