1. RE: Replacing characters

Hi Irv,

i think your solution only replaces a single character with another 
single character. if that is all Marcus wants then I suggest this 
one-liner:

string += (string = oldchar) *  (newchar - oldchar)

Mike

Irv Mullins wrote:
> On Friday 01 February 2002 05:00 pm, Marcus wrote:
> 
> > How do you search and replace characters in a  sequence?
> >
> > I need to replace \ with \\ and vice versa.
> >
> 
> You can create a sequence containing the locations of 
> any matching characters, and then replace those:
> 
> -- lightly tested :p
> 
> sequence text, matches
> atom pattern, replacement
> 
> puts(1,"Enter a string:\n")
> text = gets(0)
> pattern = '\\' -- have to escape a backslash
> replacement = '@'
> 
> matches = {}
> for i = 1 to length(text) do
>   if text[i] = pattern then
>   matches &= i
>   end if
> end for
> 
> ? matches -- see the list of places that matched
> 
> for i = 1 to length(matches) do
>   text[matches[i]] = replacement
> end for
> 
> puts(1,text)
> 
> Regards,
> Irv

new topic     » topic index » view message » categorize

2. RE: Replacing characters

> -----Original Message-----
> From: lists at wordit.com [mailto:lists at wordit.com]
> 
> How do you search and replace characters in a  sequence?
> 
> I need to replace \ with \\ and vice versa.
> 
> Thanks,
> 
> Marcus

This came up about a month or so ago.  Here's what I use (tested):

-- replaces all instances of a with b in text
function replace_all( sequence text, object a, object b )
    integer ix, jx
    
    if atom(a) then
        a = {a}
    end if
    
    if atom(b) then
        b = {b}
    end if
    
    ix = 0
    jx = match( a, text )
    while jx do
        ix += jx 
        text = text[1..ix-1] & b & text[ix+length(a)..length(text)]
        ix += length(b)
        jx = match( a, text[ix+length(a)..length(text)] )
    end while
    
    return text
    
end function

Matt Lewis

new topic     » goto parent     » topic index » view message » categorize

Search



Quick Links

User menu

Not signed in.

Misc Menu