Return to Archive

SAS Tip of the Month
October 2005

The COMPARE function compares two strings and notes the position of the first character (left to right) where it finds a difference – if no difference is found then a zero will result. The following example shows its use:

   167 data _null_;
   168 length flag1 flag2 $80;
   169 string1='THE COW JUMPED OVER THE MOON';
   170 string2='THE COW JUMPED OVER THE MOON';
   171 string3='THE COW JUMPED OVER THE BLUE MOON';
   172 compare1=compare(string1,string2);
   173 compare2=compare(string1,string3);
   174 if compare1>0 then
   175 flag1='String 1 and String 2 different starting at position '
   176 ||put(compare1,2.);
   177 else flag1='String 1 and String 2 same';
   178 if compare2>0 then
   179 flag2='String 1 and String 3 different starting at position '
   180 ||put(compare2,2.);
   181 else flag2='String 1 and String 3 same';
   182 put string1= /
   183 string2= /
   184 flag1= //
   185 string1= /
   186 string3= /
   187 flag2=;
   188 run;

   string1=THE COW JUMPED OVER THE MOON
   string2=THE COW JUMPED OVER THE MOON
   flag1=String 1 and String 2 same

   string1=THE COW JUMPED OVER THE MOON
   string3=THE COW JUMPED OVER THE BLUE MOON
   flag2=String 1 and String 3 different starting at position 25
________________________________
Updated October 1, 2005