簡體   English   中英

Turbo Pascal:檢查字符串是否包含數字

[英]Turbo Pascal: check if string contains numbers

就像標題中所說的那樣,我很難找到有關如何檢查字符串PW包含數字的解決方案。 如果字符串PW包含數字,如何檢查TP?

repeat
        writeln;
        writeln('Ok, please enter your future password.');
        writeln('Attention: The Text can only be decoded with the same PW');
        readln(PW);
        pwLength:= Length(PW);
        error:=0;
          for i:= 1 to Length(PW) do begin
            if Input[i] in ['0'..'9'] then begin
            error:=1;
            end;
          end;

           if Length(PW)=0 then
           begin
           error:=1;
           end;

            if Length(PW)>25 then
            begin
            error:=1;
            end;

        if error=1 then
        begin
        writeln('ERROR: Your PW has to contain at least 1character, no numbers and has to be under 25characters long.');
        readln;
        clrscr;
        end;

      until error=0;

這就是我編寫您的代碼的方式:

var
  PW : String;
  Error : Integer;

const
  PWIsOk = 0;
  PWIsBlank = 1;
  PWTooLong = 2;
  PWContainsDigit = 3;

procedure CheckPassword;
var
  i : Integer;
begin

  writeln;
  writeln('Ok, please enter your future password.');
  writeln('Attention: The Text can only be decoded with the same PW');
  writeln('Your password must be between 1 and 25 characters long and contain no digits.');

  repeat
    error := PWIsOk;
    readln(PW);

    if Length(PW) = 0 then
      Error := PWIsBlank;

    if Error = PWIsOk then begin
      if Length(PW) > 25 then
        Error := PWTooLong;
      if Error = 0 then begin
        for i := 1 to Length(PW) do begin
          if (PW[i] in ['0'..'9']) then begin
            Error := PWContainsDigit;
            Break;
          end;
        end;
      end;
    end;

    case Error of
      PWIsOK : writeln('Password is ok.');
      PWIsBlank : writeln('Password cannot be blank.');
      PWTooLong : writeln('Password is too long.');
      PWContainsDigit : writeln('Password should not contain a digit');
    end; { case}
  until Error = PWIsOk;
  writeln('Done');
end;

以下是一些注意事項:

  • 不要使用相同的錯誤代碼值來表示不同類型的錯誤。 對不同的錯誤使用相同的值只會增加調試代碼的難度,因為您無法確定哪個測試為Error賦予了值1。

  • 定義常量以表示不同類型的錯誤。 這樣,讀者就不必懷疑if error = 3 ... “ 3是什么意思” if error = 3 ...

  • 一旦您在密碼中檢測到數字字符,便沒有必要檢查其后面的字符,因此,我的for循環中的Break了。

  • 如果我是一個用戶,我會很生氣,直到程序告訴我做錯了什么,才告訴他們規則是什么。 事先告知使用規則。

  • 實際上,最好包括一個額外的常量Unclassified ,其值為-1,然后通過為其分配Error來開始循環的每次迭代,並在隨后的步驟中測試Error = Unclassified而不是PWIsOk

  • case陳述是一種基於序數值選擇多個互斥執行路徑之一的整潔且易於維護的方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM