[Lazarus] Checking characters in a string
silvioprog
silvioprog at gmail.com
Wed Mar 12 19:08:07 CET 2014
2014-03-12 13:35 GMT-03:00 Howard Page-Clark <hdpc at talktalk.net>:
> If you restrict yourself to Latin ansi encoding and 'number' means a
> numeric digit which does not have to be a whole word, the code is fairly
> simple since almost no parsing is required. Other cases and encodings
> require more complex string parsing. For example:
It is not hard to allow chars like "ã", "Ã", "ñ", "Ñ", "ç", "Ç", "ä", "Ä"
etc. I left the function a little faster too:
// old
function Valid(const s: string): boolean;
function HasLowerUpperNumeric: boolean;
var
c: char;
lower: boolean = False;
upper: boolean = False;
numeric: boolean = False;
begin
Result := False;
for c in s do
begin
if c in ['a'..'z'] then
lower := True
else if c in ['A'..'Z'] then
upper := True
else if c in ['0'..'9'] then
numeric := True;
if lower and upper and numeric then
Exit(True);
end;
end;
begin
if Length(s) < 3 then
Exit(False);
Result := HasLowerUpperNumeric;
end;
// new
function ValidPassword(const S: string): Boolean;
var
P: PChar;
F: Boolean;
L: Boolean = False;
U: Boolean = False;
N: Boolean = False;
begin
P := PChar(S);
while P^ <> #0 do
begin
case P^ of
#48..#57: N := True;
#65..#90: U := True;
#97..#122: L := True;
else
F := P^ = #195;
if F then
case P[1] of
#128..#159: U := True;
#160..#191: L := True;
end;
end;
Inc(P);
end;
Result := L and U and N;
end;
{ TForm1 }
procedure TForm1.Button1Click(Sender: TObject);
const
c = 20000000;
var
i: integer;
b, e: TDateTime;
s: string = 'Ãç1';
x: Boolean;
begin
// test Valid efficiency/performance
b := now;
for i := 0 to c do
begin
x := False;
x := Valid(s);
end;
e := now;
Edit1.Text := 'Valid: ' + BoolToStr(x, True) + ' - ' +
formatdatetime('hh:nn:ss:zzz', b - e);
// test ValidPassword efficiency/performance
b := now;
for i := 0 to c do
begin
x := False;
x := ValidPassword(s);
end;
e := now;
Edit1.Text := Edit1.Text + ' / ValidPassword: ' + BoolToStr(x, True) + '
- ' + formatdatetime('hh:nn:ss:zzz', b - e);
end;
Result: Valid: *False* - 00:00:00:*861* / ValidPassword: *True* - 00:00:00:
*559*
Sure, it's a function that did just for explain, then it can be easily
improved.
--
Silvio Clécio
My public projects - github.com/silvioprog
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.lazarus-ide.org/pipermail/lazarus/attachments/20140312/5a01cf59/attachment-0003.html>
More information about the Lazarus
mailing list