2017-10-06 65 views
2
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語句,並且我的代碼沒有按照我想要的方式工作。基本上,我正在制定一個程序,檢查用戶輸入的大小寫字母和數字以外的任何內容。這個問題是不同的,因爲我正在尋找如何使用Case Of語句解決這個問題。如何在Delphi中爲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; 

我也試着像這樣做,但後來意識到這是行不通的,因爲如果一個聲明是滿意的,其他人也不會和計點積分制將不能工作。

+0

什麼是你的,當然目前的話題?你有什麼需求來解決這個任務嗎?否則,您可能需要查看一組char。 – nil

+0

乾杯,我結束了使用像97..122爲字母表 –

回答

7

很高興您自己找到答案。

另一種確保密碼只包含大小寫字符和數字的方法是我試圖指出的:定義一個有效的字符set,並檢查密碼中的每個字符是否爲in這些有效字符。

所以像這樣定義的一組:

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

你可以使用之類的語句

if password[I] in ValidChars then

此語句但是會產生Unicode的德爾福編譯器警告,如在類型集限於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; 
+1

''''..'/''應該類似於你要做的事。 33..47。我目前無法驗證,所以這沒有經過測試。那不包括|和我認爲的英鎊符號。 – nil

+0

傳說,現在,我已將所有允許的符號添加到該集合中,這就像一種魅力。我最終單獨添加它們。 –

+2

這真的是適合這項任務的解決方案。很高興你選擇它作爲接受的答案。 –

1

感謝上面的評論,我找到了一個解決方案。我結束了使用這樣一個案例:

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; 

再次感謝。

6

多個範圍是在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。如果您使用unicode應用程序並且不希望字符限制爲英文字母,則可以使用TCharHelper.IsLetterOrDigit

if password[counter].IsLetterOrDigit then ... 
+0

套聲明感謝,這基本上是我想出了。 –

+0

爲什麼不簡單'如果Ord(密碼[counter])在[48..57,65 ..90,97..122]然後?看起來更簡單。請注意,該設置將被編譯爲常量。 –

+0

@RudyVelthuis,如果您不知道,編譯器會在兩種情況下生成相同的代碼。所以這更多的是個人喜好選擇哪種解決方案。 –