我正在制作一个用于学习目的的程序,这就是我使用递归来获得更多分数的原因,尽管迭代方法会更加可行。我已经使用此算法验证电子邮件地址,以确保其格式为L@L.L.我正在使用递归来验证每个实例中的每个char。一旦递归到达步骤6,那么电子邮件是有效的,否则我希望该函数返回false。有人可以请帮助我,因为我当前的解决方案必须使用全局变量,否则每个实例都会将局部变量重置为false。我知道算法并不完美,但我真的不想使用全局变量,因为它将成为一个庞大程序的一部分。
我不知道如何做的一些可能的解决方案: 1.在每个递归实例中传递一个布尔值,并在最终实例中将其设置为true。这可能是由ref或val以某种方式使用?然后将其传回堆栈 2.使用函数本地的局部变量,而不是每个在经历时都不会改变的实例
无论如何这里是代码:
var
Valid:boolean;
Function ValidEmail(Email:string; I:integer; Step:integer):boolean;
const
AlphaChars=['a'..'z', 'A'..'Z'];
begin
case Step of
1:If Email[I] in AlphaChars then
ValidEmail(Email, I+1, 2);
2:If Email[I] in AlphaChars then
ValidEmail(Email, I+1, 2)
else if Email[I] = '@' then
ValidEmail(Email, I+1, 3);
3:If Email[I] in AlphaChars then
ValidEmail(Email, I+1, 4);
4:If Email[I] in AlphaChars then
ValidEmail(Email, I+1, 4)
else if Email[I]='.' then
ValidEmail(Email, I+1, 5);
5:If Email[I] in AlphaChars then
ValidEmail(Email, I+1, 6);
6:Valid:=True;
end;
if Valid then
ValidEmail:=true;
end;
如果电子邮件是从主程序传递的电子邮件,则我是每个字符的计数,步骤是验证的距离。
答案 0 :(得分:3)
我想这可能是你的意思:
Function ValidEmail(Email:string; I:integer; Step:integer):boolean;
const
AlphaChars=['a'..'z', 'A'..'Z'];
begin
case Step of
1:If Email[I] in AlphaChars then
Result := ValidEmail(Email, I+1, 2);
2:If Email[I] in AlphaChars then
Result := ValidEmail(Email, I+1, 2)
else if Email[I] = '@' then
Result := ValidEmail(Email, I+1, 3);
3:If Email[I] in AlphaChars then
Result := ValidEmail(Email, I+1, 4);
4:If Email[I] in AlphaChars then
Result := ValidEmail(Email, I+1, 4)
else if Email[I]='.' then
Result := ValidEmail(Email, I+1, 5);
5:If Email[I] in AlphaChars then
Result := ValidEmail(Email, I+1, 6);
//6:
else
Result := True;
end;
end;
请注意,这不依赖于任何全局变量 - 您可以递归调用ValidEmail,
Function ValidEmail(Email:string; I:integer; Step:integer):boolean;
const
AlphaChars=['a'..'z', 'A'..'Z'];
begin
case Step of
...
7 : Result := ValidEmail(EMail, i, SomeOtherStep);
else
Result := True;
end;
end;
答案 1 :(得分:0)
根据Craig的评论,我已修改算法以允许数字等。
Function ValidEmail(Email:string; I:integer; Step:integer):boolean;
const
AlphaChars=['a'..'z', 'A'..'Z'];
IntChars=['1'..'9'];
CharChars=['!', '#', '$', '%' ,'&', '*', '+', '-', '/', '=', '?', '^', '_', '`', '{', '|'
, '}', '~', '.'];
begin
case Step of
1:If (Email[I] in AlphaChars) or (Email[I] in IntChars) or (Email[I] in CharChars)then
Result := ValidEmail(Email, I+1, 2);
2:If (Email[I] in AlphaChars) or (Email[I] in IntChars) or (Email[I] in CharChars)then
Result := ValidEmail(Email, I+1, 2)
else if Email[I] = '@' then
Result := ValidEmail(Email, I+1, 3);
3:If (Email[I]= '-' ) or (Email[I] in AlphaChars) or (Email[I] in IntChars) then
Result:=ValidEmail(Email, I+1, 4);
4:If (Email[I]= '-' ) or (Email[I] in AlphaChars) or (Email[I] in IntChars) then
Result:=ValidEmail(Email, I+1, 4)
else if Email[I]='.' then
Result := true;
else
Result:=false;
end;
end;