[Date Prev] [Date Next] [Thread Prev] [Thread Next] Date Index Thread Index Search archive:
Date:Mon Aug 15 16:39:25 2003 
Subject:Re: listing directories and chario 
From:steve 
Volume-ID:1030815.02 

Hi David,

>OK, the pop11 part of the server is just about finished... have a look
>(attached gzip file). I just need to know how to replace a substring...
>for example
>
>replace('hello, world', 'he', 'lox')=>
>** loxllo, world
>
>but that shouldn't be hard to do (is there a procedure that does it already?

I don't know of one ... odd ... must be one somewhere .... OK here we
go ....

Assuming you want just the first match replaced, I would write it this
way

define replace( source, find_str, substitute_str );
    lvars n = issubstring( find_str, source );
    if n then
        ;;; Going to repeatedly calculate these:
        lvars source_len = source.datalength;
        lvars find_len = find_str.datalength;
        lvars subst_len = substitute_str.datalength;

        ;;; Make a result string of the right size.
        lvars result = inits( source_len - find_len + subst_len );
        ;;; Copy the characters before the match.
        move_bytes( 1, source, 1, result, n - 1 );
        ;;; Copy the characters from the substitute string.
        move_bytes( 1, substitute_str, n, result, subst_len );
        ;;; Copy the characters after the match.
        lvars n1 = n + find_len;
        move_bytes( n1, source, n + subst_len, result, source_len - n1 + 1 );
        result
    else
        source      ;;; unchanged
    endif
enddefine;

If you want to substitute everywhere you should be a little bit smarter.
It probably still makes sense to preflight the set of matches.  Just
dump the matches on the stack as you go (avoids allocating heap, yes?).
Then from the count of the stuff dumped on the stack and the difference
in length between the find_str and substitute_str compute the length
of the result.  Then iterate over the dumped positions filling in the
string as you go.

Or, stuff efficiency, and just repeatedly do the core of the above
algorithm until there are no more matches.

-- 
Steve