Notifications
Clear all

[Closed] Replace Token's in a string

I know this has to be a really stupid question, but I haven’t yet found a decent method to do this…

Basically, I want to replace all the occurances of one string with another…ie

“This is a string”, replace “is” with “ain’t” so it reads “This ain’t a string”

I know there is a replace method, but it seems more like a fancy insert method.

My current method runs something like this…

local lstFilter = filterString "This is a string" "is"
 				
 if lstFilter.count > 0 do (
 					
   local sBuild = lstFilter[1]
   for iIndex = 2 to lstFilter.count - 1 do (
 						
 	sBuild += "ain't"
 						
   )
 					
   sBuild += lstFilter[lstFilter.count]
 				    
 )

Although, I’ve just thought of another way.

I was curious what other people do…

Shane

5 Replies

Are you using 2008? Because there’s always the AVG substituteString() method. The only downside is it replaces ALL instances, not just whole words, so:

str = "This is a string"
substituteString str "is" "ain't"

Would result in

"Thain't aint a string"
1 Reply
(@rustyknight)
Joined: 11 months ago

Posts: 0

Arrrghhh!!!

edt: Take two…

No, using max8 and 9


fn replaceWordInString thestr theword toreplace = (
	 local instring = filterString thestr theword
	 local outstring = ""

	 for i=1 to instring.count where instring[i] == theword do instring[i] = toreplace

	 -- rebuild string
	 for i=1 to instring.count do outstring += (instring[i] + " ")
	 outstring
)

test = replaceWordInString "Max script is amazing!" "script" "scripting"
print test

I’m not near a max installation, but this should work, I’m sure it could even be simpler than I have it.

-Colin

Here’s the replace function I wrote for maxToR a while back:


   -- replace all occurances of 'old' with 'new' in 'str'.
   -- returns a new string
   fn replace2 str old new =
   (
   	local findindex
   	do (
   		findindex = findString str old
   		if findindex != undefined then
   		(
   			str = replace str findindex old.count new
   		)
   	)
   	while findindex != undefined
   	str
   )
   

Example:


   replace2 "Hello World! World!" "World" "Jim"
  => "Hello Jim! Jim!"
   

Ha scorp, moondoggie! Thanks for feedback, nice to see how other people approach a common problem.

Scrop, that looks very close to the idea I’ve had…although I did find a “small” problem with it (but in my case it’s not that big a deal right now), if I use my original example, replacing “is” with “isn’t” will cause an infinate loop (that’s my solution, not yours, I believe the way you’ve constructed your loop will solve the issue)

Cheers
Shane