Author |
Topic: Stringlib, FN_findreplace not replacing all (Read 348 times) |
|
svein
New Member
member is offline


Posts: 15
|
 |
Stringlib, FN_findreplace not replacing all
« Thread started on: Jan 1st, 2017, 6:56pm » |
|
I have found an oddity in FN_findreplace, it does not always replace as requested. In the following snippet, spaces have been replaced with dots for clarity. The expected output is: ".a.b.c." not ".a....b..c..." If one REMout the 'I%+=LEN(N$)' line, then the output is correct. Anything unforeseen by removing this line ?
Svein
Code: a$="..a.......b...c......" J%=FN_findreplace(a$,"..",".",0) PRINT a$ END DEF FN_findreplace(RETURN A$,O$,N$,I%) LOCAL C% REPEAT I% = INSTR(A$,O$,I%) IF I% THEN A$ = LEFT$(A$,I%-1)+N$+MID$(A$,I%+LEN(O$)) I% += LEN(N$) C% += 1 ENDIF UNTIL I% = 0 = C%
|
|
Logged
|
|
|
|
Richard Russell
Administrator
member is offline


Posts: 803
|
 |
Re: Stringlib, FN_findreplace not replacing all
« Reply #1 on: Jan 1st, 2017, 9:29pm » |
|
on Jan 1st, 2017, 6:56pm, svein wrote:| The expected output is: ".a.b.c." not ".a....b..c..." |
|
Why? The first is surely an incorrect result. The input string is this:
Code: To clarify precisely where each of the ".." sub-strings (which you want to be replaced) are, here is the string with each occurrence substituted by a pair of numbers (so 11 signifies the first occurrence of "..", 22 the second occurrence and so on):
Code: That is, the sub-string ".." appears precisely eight times (I have arbitrarily assigned the sub-strings from left to right). If each of those eight occurrences is replaced by the string "." this is the result:
Code: which is indeed the output produced! What you claim to be the "expected" output would only result if the replacement operation was repeated until no further substitutions take place:
Code: a$="..a.......b...c......" REPEAT J%=FN_findreplace(a$,"..",".",0) UNTIL J% = 0 PRINT a$ I cannot see how it could ever be correct after a single pass.
Quote:| Anything unforeseen by removing this line ? |
|
I don't know about "unforeseen" but it will result in the function producing an incorrect output in the case of your example, and also risks an 'infinite loop' when the function never returns. For example:
Code: a$ = "aaa" PRINT FN_findreplace(a$, "a", "aa", 1) Richard.
|
|
|
|
svein
New Member
member is offline


Posts: 15
|
 |
Re: Stringlib, FN_findreplace not replacing all
« Reply #2 on: Jan 2nd, 2017, 07:26am » |
|
>output would only result if the replacement operation was repeated until no further substitutions take place< That is what i expected, clearly i have misunderstood the use of FN_findreplace.
Infinite loops is in the unforeseen category.
Changing my code to: WHILE FN_findreplace(a$,"..",".",0) : ENDWHILE
Thank you. Svein
|
|
Logged
|
|
|
|
|