Page 1 of 1

string compare

PostPosted: Sat Feb 24, 2018 2:21 pm
by dhs
Hi all,
As far as I am aware, Classic DCAL offers no way to compare strings (strcomp tests for equality only, but I want to know which is greater so that I can sort in alphabetic order).
In order to sort strings I have had to resort to some rather complex code. Although I am '100%' sure that DCAL does not offer a simple way to do it, I thought I would check with your combined wisdoms just in case my 100% assuredness is misguided and there is in fact a simple way to do it.
Thanks,
David H.

Re: string compare

PostPosted: Sat Feb 24, 2018 4:21 pm
by dhs
OK, ... as usual I posted a question and then pretty much immediately came up with a simpler solution ...

I hadn't realised that you could treat a string as an array of CHAR .
My string compare logic is now reasonably simple (code pasted below):

Code: Select allFUNCTION MyStrComp (str1, str2 : IN string; ignorecase : boolean) : integer;
!!! return -1 if str1 < str2, 1 if str1 > str2, 0 if they are equal)
VAR
      i, len1, len2, minlen : integer;
      s1, s2 : str255;
BEGIN
   strassign (s1, str1);
   strassign (s2, str2);
   if ignorecase then
      strupcase (s1, true);
      strupcase (s2, true);
   end;
   
   len1 := strlen (s1);
   len2 := strlen (s2);
   if len1 < len2 then
      minlen := len1;
   else
      minlen := len2;
   end;
   
   for i := 1 to minlen do
      if s1[i] < s2[i] then
         return -1;
      elsif s1[i] > s2[i] then
         return 1;
      end;
   end;
   
   if len1<len2 then
      return -1;
   elsif len1 > len2 then
      return 1;
   else
      return 0;
   end;
   
END MyStrComp;