如何在 Delphi 中为 if 语句指定多个范围


    for counter := 1 to lengthofpassword do
  begin
    currentletter:=password[counter];
    currentascii:=Ord(currentletter);
    if (96<currentascii<123) OR (64<currentascii<91) OR (47<currentascii<58) then
    Writeln('valid')
    else
    asciicheck:=false;
  end;

我知道这段代码是错误的,但我这样做是为了解释我想问的问题。如何指定 if 语句的范围?以前,我弄乱了很多if语句,我的代码没有按照我想要的方式工作。基本上,我正在制作一个程序来检查用户输入中除大写和小写字母和数字以外的任何内容。这个问题是不同的,因为我正在寻找如何使用案例语句解决这个问题。

    for counter := 1 to lengthofpassword do
  begin
    currentletter:=password[counter];
    currentascii:=Ord(currentletter);
    if (currentascii<48) AND (currentascii>57) then
    asciipoints:=asciipoints+1;
    if (currentascii<65) AND (currentascii>90) then
    asciipoints:=asciipoints+1;
    if (currentascii<97) AND (currentascii>122) then
    asciipoints:=asciipoints+1;
    Writeln(asciipoints);
  end;

我也尝试这样做,但后来意识到这是行不通的,因为如果一个陈述得到满足,其他陈述就不会满足,基于积分的系统也不起作用。

很高兴你自己找到了答案。

确保密码仅包含大写和小写字符和数字的另一种方法是我试图指出的:定义有效字符set,并检查密码中的每个字符是否in这些有效字符。

因此,使用如下所示的集合:

const 
  ValidChars = ['A'..'Z', 'a'..'z', '0'..'9'];

您可以使用这样的语句

if password[I] in ValidChars then

但是,此语句将在 Unicode Delphi 中生成编译器警告,因为集合中的类型限制为 256 个可能的值,并且它们的序号必须介于 0 和 255 之间。对于具有 65.536 个值的 WideChar,情况并非如此。所以定义的set of char实际上是一个set of AnsiChar。对于此任务,这是可以接受的,因为需要检查的每个字符都是 ASCII,因此使用函数 CharInSet 不会生成编译器警告,并且如果密码包含 Unicode 字符,则具有定义的行为 - 返回False

这是生成的代码:

const 
  ValidChars = ['A'..'Z', 'a'..'z', '0'..'9'];
var
  I: Integer;
begin
  for I := 1 to passwordlength do
  begin
    if CharInSet(password[I], ValidChars) then  
      Writeln('valid')  // more likely to do nothing and invert the if statement
    else
    begin
      asciicheck := False;
      Break; // No need to look further, the check failed
    end;
  end;
end;

多个范围最好用case语句表示:

begin
  for counter := 1 to lengthofpassword do
  begin
    case Ord(password[counter]) of
      48..57,
      65..90,
      97..122 :
        Writeln('valid')
      else
        asciicheck:=false;
    end;
  end;
end;

现在,这适用于 #128

if password[counter].IsLetterOrDigit then ...

多亏了上面的评论,我找到了解决方案。我最终使用了这样的 Case Of 语句:

    for counter := 1 to lengthofpassword do
  begin
    currentletter:=password[counter];
    currentascii:=Ord(currentletter);
      case currentascii of
        97..122 : asciicheck:=true;
        65..90  : asciicheck:=true;
        48..57  : asciicheck:=true;
        else asciicheck:=false;
      end;
  end;

再次感谢。

最新更新