Replace One Instance of String or Char Range

LiveCode is the premier environment for creating multi-platform solutions for all major operating systems - Windows, Mac OS X, Linux, the Web, Server environments and Mobile platforms. Brand new to LiveCode? Welcome!

Moderators: FourthWorld, heatherlaine, Klaus, kevinmiller, robinmiller

Post Reply
dickey
VIP Livecode Opensource Backer
VIP Livecode Opensource Backer
Posts: 118
Joined: Wed Apr 08, 2009 11:54 pm

Replace One Instance of String or Char Range

Post by dickey » Mon Mar 08, 2010 9:37 pm

Hello all,

I wish to be able replace a range of chars (eg char 3 to 5) in a string with another string (say 7).

So something like "Linda closed the door" becomes "Li7 closed the door".

If you use something like

Code: Select all

replace char 3 with theCounter in theHaystack
it takes the char at position three not the position.

Alternatively is there a way to use replace whereby it only changes the first instance of the found string?

Any assistance, most appreciated.

Kind regards, Andrew

Mark
Livecode Opensource Backer
Livecode Opensource Backer
Posts: 5150
Joined: Thu Feb 23, 2006 9:24 pm
Contact:

Re: Replace One Instance of String or Char Range

Post by Mark » Mon Mar 08, 2010 9:58 pm

Hi Andrew,

Try this:

Code: Select all

put "Li7" into char 3 to 5 of theHayStack
Best,

Mark
The biggest LiveCode group on Facebook: https://www.facebook.com/groups/livecode.developers
The book "Programming LiveCode for the Real Beginner"! Get it here! http://tinyurl.com/book-livecode

dickey
VIP Livecode Opensource Backer
VIP Livecode Opensource Backer
Posts: 118
Joined: Wed Apr 08, 2009 11:54 pm

Re: Replace One Instance of String or Char Range

Post by dickey » Mon Mar 08, 2010 11:32 pm

Thanks Mark,

Your tip helped me to come at the problem differently. It's funny when you have 5 languages floating around in your head, and switching between them sometimes you need a little help to get your thinking straight.

I ended up with something like this:

Code: Select all

on mouseUp
   put "Atticus too stared at Boo Radley in surprise" into theHaystack
   put 1 into theCounter
   
   repeat while theOffset is not "0"
      put "oo" into theNeedle
      put offset(theNeedle,theHaystack) into theOffset
      put theOffset into theStart
      put theOffset + the length of theNeedle -1 into theEnd
      if theOffset > 0
      then
         put theCounter into char theStart to theEnd in theHaystack
         answer info theHaystack -- first repeat shows: "Atticus t1 stared at Boo Radley in surprise" second loop shows: "Atticus t1 stared at b2 Radley in surprise"
         add 1 to theCounter
      end if
   end repeat
end mouseUp
Lousy example, but I use this style of code (counting html tags) in a technique to automate data entry and extraction on web pages. I was just converting a module from PHP to Rev and I got stuck.

Thanks again, Andrew

Post Reply