2016-06-27 32 views
1

我在德國網站delphi-treff上學習delphi。生成隨機字符串的程序凍結

它們提供了一個函數來生成隨機字符串。

https://www.delphi-treff.de/tipps-tricks/object-pascal/strings/zufallstring-generieren/

function RandomString(strlength: integer): string; 
var 
    temp : integer; 
begin 
    randomize; 
    repeat 
    temp := random(122); //ggf. erhöhen 
    if temp in [48..57{0-1}, 65..90{A-Z}, 97..122{a-z}] then 
    //Kann um beliebige ASCII-Zeichen erweitert werden, 
    //ggf. den Wert in Random hochsetzen 
     result := result + Chr(temp); 
    until length(result) = strlength; 
end; 

,你可以在這裏看到:

if temp in [48..57{0-1}, 65..90{A-Z}, 97..122{a-z}] then 

他們只放0-1,A-Z和A-Z的字符。

但是我認爲我的程序因爲這個函數而崩潰了。

所以我改變了:直到length(result)= strlength;

to:until length(result)> = strlength;

實際上它有時是> strlength。

有人可以解釋爲什麼它更大嗎?

它不應該更大,因爲它一次只能增加1個字符?

+0

Result'在循環之前未被初始化,因此長度溢出。 'Randomize'只能在程序啓動時初始化一次。 –

+0

@LURD等結果得到一個隨機值的初始化比字符串長,因此永遠不會符合標準? – Thomas

+0

請參閱[Delphi中'Result'的默認值是什麼?](http://stackoverflow.com/questions/5336863/what-is-the-default-value-of-result-in-delphi)。 –

回答

4

Result被視爲隱含的var參數,必須在使用前初始化。見What is the default value of 'Result' in Delphi?

在這種情況下,未初始化的參數Result會導致長度溢出。

另一個問題,Randomize應該只在程序啓動時調用一次。

+1

結果*從不*未初始化,但它也不一定是空的。 –