compare
Moderator: Board moderators
compare
Could anyone write an efficient compare function to compare two strings plz
-
- Guru
- Posts: 1080
- Joined: Thu Dec 19, 2002 7:37 pm
Try this:
[pascal]program test;
function scompare(var s1,s2:ansistring):integer;
var
l1,l2,minlen,i:integer;
begin
l1:=length(s1);
l2:=length(s2);
if (l1<l2) then minlen:=l1 else minlen:=l2;
i:=1;
while ((i<=minlen) and (s1=s2)) do inc(i);
if (i>minlen) then scompare:=l1-l2 else scompare:=ord(s1)-ord(s2);
end;
var
s1,s2:ansistring;
c:integer;
begin
s1:='smallest';
s2:='biggest';
c:=scompare(s1,s2);
if (c<0) then writeln('"',s1,'" is smaller than "',s2,'"')
else if (c=0) then writeln('"',s1,'" and "',s2,'" are equal')
else writeln('"',s1,'" is bigger than "',s2,'"');
end.[/pascal]
[pascal]program test;
function scompare(var s1,s2:ansistring):integer;
var
l1,l2,minlen,i:integer;
begin
l1:=length(s1);
l2:=length(s2);
if (l1<l2) then minlen:=l1 else minlen:=l2;
i:=1;
while ((i<=minlen) and (s1=s2)) do inc(i);
if (i>minlen) then scompare:=l1-l2 else scompare:=ord(s1)-ord(s2);
end;
var
s1,s2:ansistring;
c:integer;
begin
s1:='smallest';
s2:='biggest';
c:=scompare(s1,s2);
if (c<0) then writeln('"',s1,'" is smaller than "',s2,'"')
else if (c=0) then writeln('"',s1,'" and "',s2,'" are equal')
else writeln('"',s1,'" is bigger than "',s2,'"');
end.[/pascal]
like strings
Well, I heard that I can use something like string1>string2, but I'm not sure, in the acm.uva.es/p part of pascal known problems, they say that in gpc using unix the > would fail, but with freepascal there is any problem?
-
- Guru
- Posts: 1080
- Joined: Thu Dec 19, 2002 7:37 pm
thnx
Thnx for your help ![:D](./images/smilies/icon_biggrin.gif)
![:D](./images/smilies/icon_biggrin.gif)