Translate #3 - inspired by Rob Mintner
Posted in 1993
Folks,
A third way to look at this problem - which appears to run a hair faster.
My original method was to do it inline and compact/extend the string
as necesssary to accomodate the 'to' string (kludgy)
Robs method was to pop @ character into a second string until you hit the
right word and then move in the replacement, bump the indices and keep
going. The first time I read it I misinterpreted it and thought he was
doing what I present now.
This method splits the string and pops it into a second string then moves it
back.
I'm still interested in other ways to look at this, but have to go on and
do that real work thing (although I needed this function for real work so
I really am working - HONEST!).
j.
-------- cut here ----------------------------------------------------------
DATABASE xxxx
MAIN
DEFINE junk CHAR(512)
# test data - original
LET junk =
"SELECT * FROM table WHERE foo_field MATCHES 'XYZ*' OR foo_field IS NULL"
DISPLAY junk CLIPPED
# test data - to is shorter
CALL translate("foo_field", "fieldA", junk) RETURNING junk
DISPLAY junk CLIPPED
# test data - to is longer
CALL translate("fieldA", "foo_field", junk) RETURNING junk
DISPLAY junk CLIPPED
# test data - to is same length
CALL translate("foo_field", "abcdefghi", junk) RETURNING junk
DISPLAY junk CLIPPED
END MAIN
#############################################################################
# translate all occurences of 'from' in 'strg' to 'to'
#############################################################################
FUNCTION translate(from, to, strg)
DEFINE
from, to CHAR(20),
o_strg, strg CHAR(512),
idx, f_len, t_len, s_len SMALLINT,
bound, end_pos SMALLINT
# get the lengths of all parties
LET f_len = LENGTH(from)
LET t_len = LENGTH(to)
LET s_len = LENGTH(strg)
LET bound = s_len - f_len + 1
# find the string
LET idx = 0 # can't use a FOR, length may change
WHILE idx <= bound
LET idx = idx + 1
LET end_pos = idx + f_len - 1 # end of subscript
IF from = strg[idx,end_pos] THEN
LET idx = idx - 1
LET end_pos = end_pos + 1
LET o_strg = strg[1,idx], to clipped, strg[end_pos,s_len]
LET strg = o_strg CLIPPED
LET s_len = LENGTH(strg)
LET idx = idx + t_len + 1
LET bound = s_len - f_len + 1 # reset boundary condition
END IF
END WHILE
RETURN strg
END FUNCTION
-------------- and here ---------------------------------------------------
j.
_____________________________________________________________________________
Jack Parker |
Hewlett Packard, BSMC Boise, Idaho, USA| Your .sig has expired, please enter
jparker@hpbs2561.boi.hp.com | a new one.
(208) 396-5388 (W) (208) 384-1623 (H) |
_____________________________________________________________________________
Any opinions expressed herein are my own and not those of my employers.
_____________________________________________________________________________