Mohammed Hamdoon
Mohammed Hamdoon

Reputation: 49

Finding a substring in a string and its position

Guys im currently working on this small code in assembly to find a substring in a string using Assembly language , so my code here can find the substring , i need help to find the postion from where this substring starts

org 100h 

.data

buf1 DB "Enter String : $"

buf2 DB 0dh,0ah,"Enter Substring to search : $"

buf3 DB 0dh,0ah,"Substring Found $",1

buf4 DB 0dh,0ah,"Substring not Found...$"

str DB 120,120 DUP(?)

str_len DW 0

substr DB 120,120 DUP (?)

substr_len DW 0

counter DW 0   

.code

;initilize Data Segment

mov ax,@DATA

mov DS,ax

;==========Input String=====

lea dx,buf1

call Display

mov dx,offset str

mov ah,0Ah

int 21h

mov bl,[str+1]

mov str_len,bx

;=======Input Substring======

lea dx,buf2

call display

mov dx,offset substr

mov ah,0Ah

int 21h

;checking if substring is in string or not

lea SI,str ;SI contain String

add SI,2

lea DI,substr ;DI contain substring

add DI,2

mov bx,substr_len

cmp str_len,bx

jg G ;CX will contain greater value

mov cx,bx

G:

        mov cx,str_len
;======Cheking if substring or not====

L:

        lodsb
        cmp al,0Dh
        je final
        cmp al,' '
        jne next

final:

        cmp counter,0
        je exit
        mov counter,0
        lea DI,substr
        add DI,2
        jmp next1

next:

        dec SI

next1:

        cmpsb
        je h
        inc counter

h:

        LOOP L

exit:
        cmp counter,0
        je Found
        lea dx,buf4
        call Display
        jmp terminate

Found:

        lea dx,buf3
        call Display

terminate:

;to terminate program
        mov ah,4ch
        int 21h
        ret

Display PROC
mov ah,09h
int 21h
ret
Display ENDP

Upvotes: 0

Views: 215

Answers (1)

Sep Roland
Sep Roland

Reputation: 39166

so my code here can find the substring

I find that very hard to believe! With so many errors it's a miracle that it even runs...

mov bl,[str+1]
mov str_len,bx

1 You only load a byte, but you write a word for which you did not clear the high half BH. Later you will be using the whole word.

mov bx,substr_len

2 You didn't even assign that substr_len variable from the input first.

  cmp str_len,bx
  jg G ;CX will contain greater value
  mov cx,bx
G:
  mov cx,str_len

3 If the inputted substring happens to be longer than the string, you need to abort because you can't hope to find a longer string inside a shorter string!

G:
  mov cx,str_len
  ;======Cheking if substring or not====

4 If anything, this CX loop counter should get loaded from the shortest string, which should be substr_len.

5 It's a mess. Please read this Q/A.

Please use the info from the link and come up with a better solution, especially one that is more readable. I am a gentle person :-) and will gladly take a look at your next effort. Don't hesitate to ask questions.

Upvotes: 1

Related Questions