Is there a faster or more efficient method?

I’m trying to replace a given text string occuring within another by a third text string. So given

Text to alter: A fine string of text
Text to look for and replace: fine
Text to replace it with: bad

I have created the following handler:

on replace_text(tText, repText, repOverlay)
if repText is in tText then
set the item_name to tText --to the name of this_item
set AppleScript’s text item delimiters to the repText
set the item_list to every text item of the tText
set AppleScript’s text item delimiters to the repOverlay
set the new_item_name to the item_list as string
set AppleScript’s text item delimiters to “”
return new_item_name
else
return tText
end if
end replace_text

where tText is the text to look in (A fine text string)
repText is the text to look for and replace if present: (fine)
repOverlay is the text to replace any found occurance : (bad)

Just curious is there is a better or more efficient process. Of course I’m trying to replace the replace function I am used to in visual basic.

Regards

GESmith

The following code is what I have used for a long time. I didn’t write it, but I use it :wink:

Looks like you are doing basicly the same thing. This code is a bit more condensed and uses the reference form to text item delimiters (if I understand correctly, references are often faster – I can’t say for sure as I’ve never really studied them).

-- Johnathan Nathan's Search & Replace routine

on snr(the_string, search_string, replace_string)
	tell (a reference to my text item delimiters)
		set {old_tid, contents} to {contents, search_string}
		set {the_string, contents} to {the_string's text items, replace_string}
		set {the_string, contents} to {the_string as Unicode text, old_tid}
	end tell
	return the_string
end snr

Hope this helps,
Brad Bumgarner, CTA

Thanks for you quick reply. I didn’t write most of my example either. Moving over to Xcode from windows .net I don’t wish to re-invent the wheel.

Your code is more compact and I’ll bet a better approach, so again, thanks, I’ll try it out.

Regards

GESmith

:cool:

In general your right: “a references to hugeVariable” or “my hugeVariable” is faster than using the original.

But in this case it doesn’t speed it up very much.

I ran both handlers with the text “The quick brown fox jumps over the lazy dog” and replaced “lazy” with “gray”:

set a to GetMilliSec
repeat 100000 times
	your_handler("The quick brown fox jumps over the lazy dog", "lazy", "gray")
end repeat
set b to GetMilliSec
(b - a) / 100000
--returned ca: 0.25 milliseconds for both handlers on my iBook G4

Model: iBook G4
AppleScript: 1.10.3
Browser: Safari 412.5
Operating System: Mac OS X (10.4)