[comp.lang.modula2] Comparing Strings...

v8902058@cc.nu.oz.au (10/13/90)

Hello...

	I'm sorry if this is a trival task, but I would like a function that
compares two strings.  There is one in the string module I have, but I really
need to see the code for it.  I would like to be able to find if a string is
equal to, less than, or greater than another string.  I tried writing a routinue
myself, but I just can't seem to do it, so I thought I'd ask.

	I wouldn't mind some code, or just the basic algorithm maybe.

	If anyone can help me, please email or post...

Thanks.

Bernard.

Patrick.Verkaik@p99.f124.n512.z2.fidonet.org (Patrick Verkaik) (10/19/90)

Hello Bernard,

In a message to All <16 Oct 90  1:06:00> Bernard wrote:

 v8> like to be able to find if a string is
 v8> equal to, less than, or greater than another string.  I tried
 v8> writing a routinue

I have seen the following (translated and slightly modified) in a book (by Jim van Keulen):

-+---------------------------------------------------------------

TYPE
     CompareType = (Smaller , Greater , Equal);

PROCEDURE CompareString (Str1 , Str2 : ARRAY OF CHAR) : CompareType;
     (* CompareString returns
      * Smaller if Str1 < Str2,
      * Equal   if Str1 = Str2,
      * Greater if Str1 > Str2 *)
VAR
     i : CARDINAL;
     LengthStr1 , LengthStr2 , LengthShortest : CARDINAL;

BEGIN
     LengthStr1 := LengthString (Str1);
     LengthStr2 := LengthString (Str2);
     IF LengthStr1 <= LengthStr2
     THEN
          LengthShortest := LengthStr1
     ELSE
          LengthShortest := LengthStr2
     END;
     FOR i := 0 TO LengthShortest DO
          IF Str1 [i] < Str2 [i]
          THEN
               RETURN Smaller
          ELSIF Str1 [i] > Str2 [i]
               RETURN Greater
          END
     END;

     (* One of either strings forms the beginning of the other *)
     IF LengthShortest < LengthStr2
     THEN
          RETURN Smaller
     ELSIF LengthShortest < LengthStr1
          RETURN Greater
     ELSE
          RETURN Equal
     END
END CompareString;

-+---------------------------------------------------------------

That's it, I've assumed you do have a procedure that returns the length of a string (LengthString or whatever yours is called) otherwise I can give you that source too, if you want it...

Hope this has helped you!

PDV

--  
uucp: uunet!m2xenix!puddle!2!512!124.99!Patrick.Verkaik
Internet: Patrick.Verkaik@p99.f124.n512.z2.fidonet.org