TJF wrote:@MichaelW:
The difference isn't big at short strings. Try longer one, like:
Code: Select all
' generate a long string
VAR s = "0123456789ABCDEF"
FOR i AS INTEGER = 0 TO 17
s &= s
NEXT
s &= "my other brother darryl"
?Replace( s, "darryl","Darryl" )
STRreplace( s, "darryl","Darryl" )
Hi JTF
I've been messing around with string replace myself over in the squares topic.
I used Function SAR (Search and replace), and I've modified it a bit for this thread, it really is similar to your own but a function.
My original SAR didn't take the shortcut for equal lengths out and in.
So thanks for that little shortcut.
As far as I can see, replace only replaces the first instance.
Ive done a couple of replacements with each procedure, but to slow both yours and mine, I've made the replacement a different length to that being replaced.
Code: Select all
FUNCTION Replace(BYREF src AS STRING,BYREF find AS STRING,BYREF repl AS STRING,start AS INTEGER=1) AS STRING
DIM source AS STRING,buf AS STRING
source = src
buf = find
DIM indx AS INTEGER = INSTR(start,source,buf)
IF indx=0 THEN RETURN ""
IF indx = 1 THEN RETURN repl & MID(source,LEN(buf)+1)
DIM n AS INTEGER = 0
DIM tmp AS STRING
DO
n+=1
IF n=indx THEN EXIT DO
tmp += MID(source,n,1)
LOOP
RETURN tmp & repl & MID(source,indx + LEN(buf))
END FUNCTION
SUB STRreplace(BYREF T AS STRING, BYREF I AS STRING, BYREF S AS STRING, BYVAL A AS INTEGER = 1)
VAR p = INSTR(A, T, I), li = LEN(I), ls = LEN(S) : IF li = ls THEN li = 0
WHILE p
IF li THEN T = LEFT(T, p - 1) & S & MID(T, p + li) ELSE MID(T, p) = S
p = INSTR(p + ls, T, I)
WEND
END SUB
Function SAR(s0 As String,s1 As String,s2 As String) As String
var lens1=Len(s1),lens2=Len(s2)
If lens1=lens2 Then lens1=0
dim as string s=s0
Dim As Integer position=Instr(s,s1)
While position>0
If lens1 Then
s=Left(s,position-1) & s2 & Mid(s,position+Lens1)
Else
Mid(s,position) = S2
End If
position=Instr(position+Lens2,s,s1)
Wend
Function=s
End Function
' generate a long string
VAR s = "0123456789ABCDEF"
FOR i AS INTEGER = 0 TO 12'17
s &= s
NEXT
dim brother as string="my other brother darryl darryl"
s &= brother
dim as string s2,s3
dim as double t1,t2,t3,t4,t5,t6
t1=timer
s2=Replace(s,"456","**")
s2=Replace( s,"darryl","Darryl" ) '' loop executes 18 times
t2=timer
t3=timer
s3=SAR(s,"456","**")
s3=SAR(s3,"darryl","Darryl" )
t4=timer
t5=timer
STRreplace( s,"456","**" )
STRreplace( s,"darryl","Darryl" ) '' loop executes 1 time
t6=timer
print "Replace ";mid(s2,len(s2)-len(brother)-20)
print "SAR "; mid(s3,len(s3)-len(brother)-20)
print "STRreplace ";mid(s,len(s)-len(brother)-20)
print "TIMES"
print "Replace ";t2-t1
print "SAR ";t4-t3
print "STRreplace ";t6-t5
print "done"
sleep