The program will ask for 2 strings (with a maximum size of 150 characters, for example).
INPUT
String 1: "Hello this is the first string"
String 2: "Woops this string is different and longer!"
OUTPUT
Number of equal characters = 26
Number of different characters = 15
I have in mind that we don't have to "calculate" the different characters as we can get the size of the longest string and subtract the number of equal characters but I don't know how to do this first comparison (the number of equal characters).
How can I do this? Could I do a macro for that comparison?
CodePudding user response:
How would you do this on paper?
You would in turn consider every character from the shorter string and try to locate it in the longer string. If you found the character then you would increment your counter, and you would strike the character from the longer string so the character could not be found a second time.
From:
-- ----------- --------- ----
Hello this is the first string
Woops this string is different and longer!
- ----------------- -- --- -- -
To:
Hello this is the first string (4 characters remain)
==> 30 - 4 = 26 are 'equal'
Woops this string is different and longer! (16 characters remain)
==> 16 are 'different'
In assembly code it could look like this:
S1 db "Hello this is the first string"
S2 db "Woops this string is different and longer!"
...
cld ; Clear direction flag
xor bx, bx ; Reset counter
mov si, S1 ; Pointer to shorter string
mov dx, 30 ; Length of the shorter string
NextChar:
lodsb ; Fetch next character from shorter string
mov di, S2 ; Pointer to longer string
mov cx, 42 ; Length of the longer string
repne scasb
jne NotFound
inc bx ; Increment counter
mov byte [di-1], 0 ; Strike by replacing with zero
NotFound:
dec dx ; Repeat for all characters in shorter string
jnz NextChar
scasb
compares AL
with the byte at [es:di]
setting flags, and increments the DI
register (provided the direction flag is cleared).
repne scasb
keeps comparing for as long as the count in CX
is not exhausted and the zero flag is not set.
I have in mind that we don't have to "calculate" the different characters as we can get the size of the longest string and subtract the number of equal characters...
That is correct.
The above code should yield next results:
Number of equal characters = 26
Number of different characters = 42 - 26 = 16