Below is a program to examine the appearance of a pattern in a string. End in line 18 represents the end of the program.
• Inputs are given to array Pat (base address $s0) of type char and Str (base address $s1). Both strings have NULL characters (\0, ASCII code 0) at the end.
• Each time a pattern Pat appears in a string Str, its leading position is stored in an integer array AP (base address $s2) and the total number of appearances is output to a register $s3. For example, if the input is Pat="ABC", Str="ABCBABC", AP[0]=0, AP1=4,8>AP=.
Main:
add$s3,$zero,$zero
add$t4,$zero,$zero
LoopO:add$t0,$s0,$zero
add$t1,$s1,$t4
LoopI:lb$t2,0($t0)
beq$t2,$zero,Find
lb$t3,0($t1)
beq$t3,$zero,Fin
bne$t2,$t3,Next
addi$t0,$t0,1
addi$t1,$t1,1
j LoopI
Find:
sw$t4,0($s2)
addi$s2,$s2,4
addi$s3,$s3,1
Next:
addi$t4,$t4,$t1
j Loop0
Fin:End
This code doesn't work, if there are no characters that match array str and array pat, $t4 is much the same value even if you jump to next, so when you jump to LOOP0, add $t1, $s1, $t4 instructions point to much the same character in array str
What should I do?
As of the start of the scan (LoopO
), you should set the value to $t4
in advance (sub$t4,$t1,$s1
).
Main:
la$s0,pat
la$s1,str
la$s2,index
add$s3,$zero,$zero
add$t1,$s1,$zero
LoopO:
add$t0,$s0,$zero
sub$t4,$t1,$s1#Set new starting index
LoopI:
lb$t2,0($t0)
beq$t2,$zero, Find
lb$t3,0($t1)
beq$t3,$zero,Fin
addi$t1,$t1,1
bne$t2,$t3,LoopO
addi$t0,$t0,1
j LoopI
Find:
sw$t4,0($s2)
addi$s2,$s2,4
addi$s3,$s3,1
addi$t1,$t1,1
j LoopO
Fin:
li$v0,10
syscall
.data
pat:.asciiz "ABC"
str:.asciiz "ABCAABCBABC"
index:.word0:10
© 2024 OneMinuteCode. All rights reserved.