Shop OBEX P1 Docs P2 Docs Learn Events
Comparing Strings — Parallax Forums

Comparing Strings

Jeff_5_Jeff_5_ Posts: 36
edited 2011-06-23 18:35 in BASIC Stamp
I am working with a Basic Stamp homework board.

I have declared

String1 VAR Byte(4)
String2 VAR Byte(4)
String3 VAR Byte(4)
String VAR Byte(7)

I have already written a function to read in and store String 1 String 2 and String 3. Now i want to read in String and compare it to String1 String2 and String 3. If string matches String1 or matches String 2 or matches String 3 then do some code.

String is 7 bytes long but i wont want to compare the first 4 bytes to String 1 String 2 and String 3

I tried this but it didn't work

Serin 1,84,[ STR String\7]

i=0
IF( (i<4) AND (String(i)=String1(i)) Then

some code
i=i+1

ELSE IF ( (i<4) AND (String(i)=String2(i)) Then

some code
i=i+1



ELSE IF ( (i<4) AND (String(i)=String3(i)) Then

some code
i=i+1

ENDIF

Comments

  • Jeff_5_Jeff_5_ Posts: 36
    edited 2011-06-23 10:18
    Can anybody help me with this ? I just want to rwead in a string and compare it to three other saved string looking for a match.
  • PJAllenPJAllen Banned Posts: 5,065
    edited 2011-06-23 11:32
    If I wanted to compare String1(0), String2(0), and String(0):

    IF (String1(0) = String2(0)) AND (String1(0) = String(0)) THEN They_are_equal


    String1(1), String2(3), String3(0), String(6)

    IF (String1(1) = String2(3)) AND (String3(0) = String(6)) AND (String1(1) = String3(0)) THEN They_are_equal

    http://forums.parallax.com/album.php?albumid=38&attachmentid=79414
    http://forums.parallax.com/album.php?albumid=38&attachmentid=79382
  • UnsoundcodeUnsoundcode Posts: 1,532
    edited 2011-06-23 18:35
    Hi, because a string is an array of bytes you have to compare each element of the target string with the corresponding element of the string being compared. Also the comparison may have to be done a maximum of three times and a minimum of once. Here is an example that has a sub routine that compares the existing strings, exiting the sub if a match is found.
    i VAR Nib
    j VAR Nib
    
    string VAR Byte(4)
    string1 VAR Byte(4)
    string2 VAR Byte(4)
    string3 VAR Byte(4)
    
    string(0)="B"
    string(1)="S"
    string(2)="."
    string(3)="2"
    
    string3(0)="B"
    string3(1)="S"
    string3(2)="."
    string3(3)="2"
    
    GOSUB  cmp_string
    DEBUG "String and String",DEC i," are the same"
    END
    
    
    cmp_string:
    i=1
    DO
    IF j=3 THEN RETURN
    j=j+1
    LOOP WHILE string(j)=string1(j)
    
    
    i=2
    j=0
    
    DO
    IF j=3 THEN RETURN
    j=j+1
    LOOP WHILE string(j)=string2(j)
    
    j=0
    i=3
    
    DO
    IF j=3 THEN RETURN
    j=j+1
    LOOP WHILE string(j)=string3(j)
    
    DEBUG "No Match was found"
    END
    

    Jeff T.
Sign In or Register to comment.