Hello everyone,
I made an function to replace substrings in a string for other substrings. I've been using it for a while and it's working very well. If anyone founds a bug or knows a way to optimize it, please let me know.
Hope it is useful for someone.
Use it like this:
invoke ReplaceString, addr String, addr OldSubString, addr NewSubString



ReplaceString proc SourceString:DWORD, SubString:DWORD, NewSubString:DWORD
LOCAL NewLenSourceString:DWORD
LOCAL LenSourceString:DWORD
LOCAL LenSubString:DWORD
LOCAL LenNewSubString:DWORD
LOCAL esi1:DWORD
LOCAL movecount:DWORD
LOCAL movemode:DWORD

pushad

mov esi, SourceString
mov edi, SourceString
mov ebx, SubString
mov edx, NewSubString

invoke lstrlen, SourceString
mov LenSourceString, eax
invoke lstrlen, SubString
mov LenSubString, eax
invoke lstrlen, NewSubString
mov LenNewSubString, eax
.IF eax>LenSubString
mov movemode, 1
.ELSE
mov movemode, 0
.ENDIF

compare1:
mov ah, [ebx]
compare1loop:
mov al, [esi]
inc esi
cmp al, 0
je theend
cmp al, ah
je compare2
jmp compare1loop

compare2:
dec esi
mov esi1, esi
compare2loop:
mov al, [esi]
inc esi
mov ah, [ebx]
inc ebx
cmp ah, 0
je found
cmp al, ah
jne backtocompare1
jmp compare2loop

backtocompare1:
mov ebx, SubString
mov esi, esi1
inc esi
jmp compare1

found:
cmp movemode, 1
je found1
mov esi, esi1
copyloop0:
mov al, [edx]
inc edx
cmp al, 0
je copydone0
mov [esi], al
inc esi
jmp copyloop0
copydone0:
xor eax, eax
xor ecx, ecx
mov ecx, LenSubString
sub ecx, LenNewSubString
mov eax, LenSourceString
sub eax, ecx
mov NewLenSourceString, eax
mov edi, esi
mov esi1, esi
add esi, ecx
moveloop0:
mov al, [esi]
inc esi
mov [edi], al
inc edi
cmp al, 0
je backtocompare3
jmp moveloop0

found1:
xor eax, eax
xor ecx, ecx
mov ecx, LenSubString
sub ecx, LenNewSubString
mov eax, LenSourceString
sub eax, ecx
mov NewLenSourceString, eax
mov esi, SourceString
add esi, LenSourceString
add edi, NewLenSourceString
xor eax, eax
xor ecx, ecx
mov eax, esi1
add eax, LenSubString
mov ecx, esi
sub ecx, eax
add ecx, 1
mov movecount, 0
moveloop:
mov al, [esi]
dec esi
mov [edi], al
dec edi
inc movecount
cmp ecx, movecount
je copynewsubstr
jmp moveloop

copynewsubstr:
mov esi, esi1
copyloop:
mov al, [edx]
inc edx
cmp al, 0
je backtocompare2
mov [esi], al
inc esi
jmp copyloop

backtocompare3:
mov esi, esi1
backtocompare2:
mov edi, SourceString
mov ebx, SubString
mov edx, NewSubString
mov eax, NewLenSourceString
mov LenSourceString, eax
jmp compare1

theend:
popad
ret
ReplaceString endp
Posted on 2002-02-03 18:19:29 by dilau