Replace 1st piece in string, then delete other parts

From NSIS Wiki
Jump to navigationJump to search
Author: Afrow UK (talk, contrib)


Description

This will replace the first piece of text it finds (e.g. hello) with (e.g. goodbye) and then if it finds any more (e.g. hello)'s then it will delete them.

Usage

Push "called" ; string to replace other
Push "hello" ; string to be replaced
Push "hello I'm hello hello hello Afrow UK"
 Call StrReplaceOnce
Pop $R0

$R0 = "I'm called Afrow UK"

The Function

Function StrReplaceOnce
Exch $0
Exch
Exch $1
Exch
Exch 2
Exch $2
Exch 2
Push $3
Push $4
Push $5
StrCpy $3 0
StrLen $5 $1
loop:
  IntOp $3 $3 + 1
  StrCpy $4 $0 $5 -$3
  StrCmp $4 "" done
  StrCmp $4 $1 0 loop
  IntOp $5 $3 - $5
  StrCpy $4 $0 -$3
  StrCpy $5 $0 $5 -$5
  StrCpy $4 $4$2$5
  StrCpy $0 $4
  StrCpy $3 0
  StrLen $5 $1
loop2:
  IntOp $3 $3 + 1
  StrCpy $4 $0 $5 -$3
  StrCmp $4 "" done
  StrCmp $4 $1 0 loop2
  IntOp $5 $3 - $5
  IntOp $5 $5 - 1
  StrCpy $4 $0 -$3
  StrCpy $5 $0 $5 -$5
  StrCpy $4 $4$5
  StrCpy $0 $4
  StrCpy $3 0
  StrLen $5 $1
Goto loop2
done:
  StrLen $1 $0
  StrCpy $2 $0 1 -$1
  StrCmp $2 " " 0 +3
  IntOp $1 $1 - 1
  StrCpy $0 $0 $1 -$1
Pop $5
Pop $4
Pop $3
Pop $2
Pop $1
Exch $0
FunctionEnd

This was written from scratch by Afrow UK on the 2nd May 2003 at 10pm. Completed on 3rd May at 12:05am

-Stu