In assembly, to compare a string, does one really have to load each Character into A and whatev, CP, and then continue if true? is there any faster way for comparing strings of predetermined but variable length?
That's the easiest, quickest way to do it, but I think it may be less bad than you imagine. Pretend that you have hl and de pointing to the first character, respectively, of your two strings that you want to compare, and b holding the length of the strings. You can compare them like so:
Code:
If you want to use this, simply set hl, de, and b, call CompareStrings, and then use the z/nz flag.
Code:
CompareStrings:
ld a,(de)
cp (hl)
ret nz ;nz means they are not equal
inc hl
inc de
djnz CompareStrings
or a ;set the z flag, which means they're equal
ret
instead of doing what Kerm said you could do
Code:
you could use an ldi
Code:
strcmp:
ld a,(de)
cpi
inc de
ret nz
djnz strcmp
or a
ret
you could use an ldi
You would also have to case for strings of different length as an early reject (if required).
Edit - Ninja'd .
Edit - Ninja'd .
Hey, look at this: Compare Strings
-
chickendude
- Expert (Posts: 502)
- 26 Nov 2014 12:08:04 am
- Last edited by chickendude on 26 Nov 2014 10:29:27 am; edited 1 time in total
With cpi you also need to be careful that c doesn't drop below 0.
Assuming strings are stored like this:
Code:
you could just do this:
Code:
Assuming strings are stored like this:
Code:
text_str1:
.db 6
.db "STRING"
text_str2:
.db 7
.db "STRING2"
you could just do this:
Code:
ld hl,text_str1
ld de,text_str1
strcmp:
ld a,(de)
cpi
inc de
ret nz
ld b,a
ld c,a ;make sure there's no carry over into b with c reaching 0
strcmp_loop:
ld a,(de)
cpi
inc de
ret nz
djnz strcmp_loop
or a
ret
DrDnar wrote:
You forgot to compare the two lengths. He said the lengths are known, after all.
For some reason I read "the lengths are known and equal" rather than "the lengths are known". Thanks for pointing that out. And Mateo: Nice catch! We should use this as an opportunity to make sure that ASM in 28 Days is actually suggesting good code, and correct it otherwise. Register to Join the Conversation
Have your own thoughts to add to this or any other topic? Want to ask a question, offer a suggestion, share your own programs and projects, upload a file to the file archives, get help with calculator and computer programming, or simply chat with like-minded coders and tech and calculator enthusiasts via the site-wide AJAX SAX widget? Registration for a free Cemetech account only takes a minute.
» Go to Registration page
» Go to Registration page
Page 1 of 1
» All times are UTC - 5 Hours
You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot vote in polls in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot vote in polls in this forum
Advertisement