文章目录
目的
写这个程序的目的是生成一个密码和用于快递的名字(生成密码和姓名),并且记下用于哪个电商平台(备注),然后进行保存(导出txt)。为了持续存储,我选择了以不覆盖的方式写入密码和姓名(追加写入)。
效果图
密码生成器类
unit PasswordGenerator;
interface
uses
Windows, SysUtils, Classes, StrUtils;
{TPasswordGenerator 类封装了密码生成的功能}
type
TPasswordGenerator = class
private
FAllowedChars: string; //大小写字母、数字和一系列特殊字符
FPasswordLength: Integer; //密码长度
FGeneratedPasswordsList: TStringList; //用来装生成的密码
function GenerateChar: Char;
public
constructor Create(passwordLength: Integer; allowedChars: string);
procedure GeneratePasswords(count: Integer);
property GeneratedPasswords: TStringList read FGeneratedPasswordsList;
end;
implementation
{构造函数,接受密码长度和允许的字符集作为参数。}
constructor TPasswordGenerator.Create(passwordLength: Integer; allowedChars: string);
begin
inherited Create;
FPasswordLength := passwordLength;
FAllowedChars := allowedChars;
FGeneratedPasswordsList := TStringList.Create;
Randomize; // 初始化随机数生成器
end;
{用于生成一个随机的字符。}
function TPasswordGenerator.GenerateChar: Char;
var
randomIndex: Integer;
begin
randomIndex := Random(Length(FAllowedChars)) + 1;
Result := FAllowedChars[randomIndex];
end;
{生成指定数量的密码,并将它们存储在 FGeneratedPasswordsList 字符串列表中。}
procedure TPasswordGenerator.GeneratePasswords(count: Integer);
var
i, j,n: Integer;
password: string;
begin
FGeneratedPasswordsList.Clear;
for i := 1 to count do
begin
password := '';
for j := 1 to FPasswordLength do
begin
password := password + GenerateChar;
end;
FGeneratedPasswordsList.Add(password);
end;
end;
end.
这段代码定义了一个名为 TPasswordGenerator
的Delphi类,该类封装了生成随机密码的功能。以下是代码逻辑的简要概括及作用:
类定义
- TPasswordGenerator 类是一个用于生成随机密码的类。
- 它有三个私有成员变量:
FAllowedChars
:一个字符串,包含了生成密码时可以使用的字符集(如大小写字母、数字和特殊字符)。FPasswordLength
:一个整数,表示生成的密码的长度。FGeneratedPasswordsList
:一个TStringList
对象,用于存储生成的密码列表。
成员函数
-
构造函数
Create(passwordLength: Integer; allowedChars: string)
:- 接受两个参数:密码长度(
passwordLength
)和允许的字符集(allowedChars
)。 - 初始化
FPasswordLength
和FAllowedChars
成员变量。 - 创建一个新的
TStringList
实例来存储生成的密码,并调用Randomize
来初始化随机数生成器。
- 接受两个参数:密码长度(
-
GenerateChar
函数:- 生成并返回一个随机的字符,该字符来自
FAllowedChars
字符串。 - 使用
Random
函数生成一个随机索引。
- 生成并返回一个随机的字符,该字符来自
-
GeneratePasswords(count: Integer)
过程:- 接受一个整数参数
count
,表示要生成的密码数量。 - 清空
FGeneratedPasswordsList
列表。 - 通过两层循环生成指定数量的密码:外层循环控制生成的密码数量,内层循环根据
FPasswordLength
拼接生成单个密码。 - 每个生成的密码都添加到
FGeneratedPasswordsList
列表中。
- 接受一个整数参数
点击“密码生成”事件
{密码生成}
procedure TForm1.Button1Click(Sender: TObject);
var
i: Integer;
allowedChars: string;
begin
// 根据CheckBox初始化允许的字符集
allowedChars := '';
if chkUpperCase.Checked then
allowedChars :=