Puzzled by string comparisons

Use this forum to post questions about syntax problems or general programming issues. Questions on implementing a particular aspect of econometrics should go in "Econometrics Issues" below.
mboldin
Posts: 5
Joined: Fri Oct 04, 2013 9:36 am

Puzzled by string comparisons

Unread post by mboldin »

I am having trouble getting %strcmp to evaluate to 1 or TRUE
The goal was to set up if statements that compare a string to a state code

if st .eq. "NJ"
did not work as I expected

So I tried if %strcmp(_) but it always evaluates to 0

I am most puzzled that the following code produces 0's

Code: Select all

compute [string] st= "NJ"
compute [string] stnj= "NJ"
display "State : " st  stnj  %strcmp(st,stnj)  %strcmp(%left(st,2),%left(stnj,2)) %strcmp("A","A")  %strcmpnc(st,stnj)  %strcmpnc("A","A")

TomDoan
Posts: 7814
Joined: Wed Nov 01, 2006 4:36 pm

Re: Puzzled by string comparisons

Unread post by TomDoan »

%strcmp(a,b) returns 0 (not 1) for a match, -1 if a<b (that is, would sort first) lexicographically and +1 if a>b.

compute state="NJ"
disp %strcmp(state,"NC") %strcmp(state,"NJ") %strcmp(state,"NY")

gives

1 0 -1

So far as I can tell, the .eq. or == seems to work.
Post Reply