我在德國網站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個字符?
Result'在循環之前未被初始化,因此長度溢出。 'Randomize'只能在程序啓動時初始化一次。 –
@LURD等結果得到一個隨機值的初始化比字符串長,因此永遠不會符合標準? – Thomas
請參閱[Delphi中'Result'的默認值是什麼?](http://stackoverflow.com/questions/5336863/what-is-the-default-value-of-result-in-delphi)。 –