Advertisement
AngryLad

6502 Substring Finding Algorithm

Feb 20th, 2024 (edited)
564
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /*
  2. Copyright-free! For any use!
  3.  
  4. KickAssembler Substring Matching Subroutine.
  5. Finds the index of the first occurence of a substring (can be any encoding, just make sure both the
  6. string and substring are the same encoding!)
  7.  
  8. Both strings MUST have a final NULL ($00 byte) character.
  9.  
  10. Store the address of the string to search at $fb
  11. Store the address of the substring at $fd
  12.  
  13. $c000 - $c002 are used as temp
  14.  
  15. A & Y registers will be used.
  16.  
  17. A <- boolean (0 or 1) on whether a match was found
  18.  
  19. X <- index of the first occurence of the substring (if found, 0 if not found
  20.  
  21. Y <- 0
  22.  
  23. __$fb - $fc, $c000 - $c002 and Y are set to zero!__
  24. */
  25.  
  26. find_substr: {
  27.     .label stri = $3b
  28.     .label subi = $3c
  29.     .label finalindex = $2a
  30.     .label stradd = $fb
  31.     .label subadd = $fd
  32.     lda #0 // index of the searched string
  33.     sta stri
  34.     lda #0 // index of the substring
  35.     sta subi
  36. mainloop:
  37.     ldy stri
  38.     lda (stradd),y
  39.     ldy subi
  40.     cmp (subadd),y
  41.  
  42.     beq letter_match
  43.     bne letter_mismatch
  44. letter_match:
  45.     // letter matches, increment substring index
  46.     inc subi
  47.     jmp check
  48. letter_mismatch:
  49.     inc finalindex
  50.     lda #0
  51.     sta subi
  52. check:
  53.     ldy subi // check substring first, to prevent substring matches at the end of the
  54.     // searched string from coming back false
  55.     lda (subadd),y
  56.     beq endsubreached // return true
  57.  
  58.     ldy stri
  59.     lda (stradd),y
  60.     beq endstrreached // return false
  61.  
  62.     inc stri
  63.     jmp mainloop
  64. endsubreached:
  65.     lda #1 // substring found
  66.     ldx finalindex
  67.     jmp end
  68. endstrreached:
  69.     lda #0
  70.     ldx #0
  71.     jmp end
  72. end:
  73.     ldy #0
  74.     sty stradd
  75.     sty subadd
  76.     sty finalindex
  77.     sty stri
  78.     sty subi
  79.     rts
  80. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement