On June 2, 2011, Ted Woollett wrote:
----------------------------------------
The function text_replace is a one-string
tool which can be used to process a text
file using higher level functions which
operate on files.
[snip]
------------------------
the code for sloc has an error at the end with the
incorrect behavior:
------------------
(%i15) sloc("this is","is",1);
(%o15) 3
(%i16) sloc("this is","is",2);
(%o16) 6
(%i17) sloc("this is","is",3);
(%o17) 6
----------------------------
The corrected code for sloc is:
----------------------------------
/*
sloc (string, substring, n) returns the
string position of the n'th appearance of
the substring, ignoring distinctness.
Returns false if no n'th appearance.
*/
sloc(bs,bo,bn) :=
block ([lbs,lbo,nbs,nsearch:0 ],
lbs : slength (bs),
lbo : slength (bo),
/* search for first substring location */
nbs : ssearch (bo,bs,sequal,1),
nsearch : nsearch + 1,
if not nbs then return (false),
if nsearch = bn then return (nbs),
if nbs + lbo -1 = lbs then return(false),
do
(nsearch : nsearch + 1,
nbs : ssearch (bo,bs,sequal,nbs+1),
if not nbs then return(),
if nsearch = bn then return(),
if nbs + lbo -1 = lbs then
( nbs:false, return())),
nbs)$
----------------------------
with the correct behavior:
-----------------------
(%i18) load(replace);
(%o18) "c:/work2/replace.mac"
(%i19) sloc("this is","is",1);
(%o19) 3
(%i20) sloc("this is","is",2);
(%o20) 6
(%i21) sloc("this is","is",3);
(%o21) false
(%i26) sloc("This is line one, isn't it? Yes, it is","is",1);
(%o26) 3
(%i27) sloc("This is line one, isn't it? Yes, it is","is",2);
(%o27) 6
(%i28) sloc("This is line one, isn't it? Yes, it is","is",3);
(%o28) 19
(%i29) sloc("This is line one, isn't it? Yes, it is","is",4);
(%o29) 37
(%i30) sloc("This is line one, isn't it? Yes, it is","is",5);
(%o30) false
-----------------------------
Ted Woollett