//Title: ReplaceText
//Credit to: Kuraudo
//Contributed by: Kuraudo
/*
replacetext(haystack, needle, replace)
Replaces all occurrences of needle in haystack (case-insensitive)
with replace value.
replaceText(haystack, needle, replace)
Replaces all occurrences of needle in haystack (case-sensitive)
with replace value.
*/
proc
replacetext(haystack, needle, replace)
var
pos = findtext(haystack, needle)
needleLen = length(needle)
replaceLen = length(replace)
while(pos)
haystack = copytext(haystack, 1, pos) + replace + \
copytext(haystack, pos+needleLen)
pos = findtext(haystack, needle, pos+replaceLen)
return haystack
replaceText(haystack, needle, replace)
var
pos = findText(haystack, needle)
needleLen = length(needle)
replaceLen = length(replace)
while(pos)
haystack = copytext(haystack, 1, pos) + replace + \
copytext(haystack, pos+needleLen)
pos = findText(haystack, needle, pos+replaceLen)
return haystack
///*
//Testing Code/Sample Implementation:
client/verb/Test()
var/hamspam = "spamspamspamSPAM"
src << replacetext(hamspam, "spam", "hamspam")
src << replaceText(hamspam, "SPAM", "HAMSPAM")
//*/
ID:195050
Jun 13 2008, 5:55 am
|
|
Jun 13 2008, 1:38 pm
|
|
Wow, I thought I had uploaded mine a long time ago. It wouldn't serve any purpose uploading it now, of course; the basic replacetext() is hard to improve upon, so it looks exactly like this.
|
In response to Jtgibson
|
|
I have a rather different version, though it still uses a loop.
proc As for its efficiency, I'm not quite sure if calling the proc over and over again or just running one loop is better than the other. Also, just a small note, that ? operator's second argument, findtext( string , fugitive ) is a bit out of place. It should be located accordingly under the above line. Then again, I guess this isn't the DM compiler and there may be different settings such as resolution affecting it, so I ought not to worry about it. |
In response to Metamorphman
|
|
Metamorphman wrote:
proc Firstly, it's important to note that yours crashes anytime fugitive occurs somewhere in replace. For example: client/verb/Test() Metamorphman wrote: As for its efficiency, I'm not quite sure if calling the proc over and over again or just running one loop is better than the other. Using simple looping structures is almost always better than recursive function calls for several reasons, some of which I'll list here:
|
In response to Kuraudo
|
|
Ah, indeed. Thanks for the explanation.
|