From 58d9d53b2ddc80c5d599f2fde3e265a4beaeccb4 Mon Sep 17 00:00:00 2001 From: Max Horn Date: Mon, 23 Oct 2023 01:00:03 +0200 Subject: [PATCH 1/2] ReplacedString: rename variables to match docs --- lib/init.g | 19 ++++++++----------- 1 file changed, 8 insertions(+), 11 deletions(-) diff --git a/lib/init.g b/lib/init.g index 6fec1b1504..cea842f139 100644 --- a/lib/init.g +++ b/lib/init.g @@ -102,18 +102,15 @@ infinity := "2b defined"; ## ## This cannot be inside "kernel.g" because it is needed to read "kernel.g". ## -ReplacedString := function ( arg ) - local str, substr, lss, subs, all, p, s, pp; - str := arg[1]; - substr := arg[2]; - lss := LEN_LIST( substr ); - subs := arg[3]; - if LEN_LIST( arg ) > 3 then - all := arg[4] = "all"; +ReplacedString := function ( str, old, new, arg... ) + local lss, all, p, s, pp; + lss := LEN_LIST( old ); + if LEN_LIST( arg ) > 0 then + all := arg[1] = "all"; else all := true; fi; - p := POSITION_SUBSTRING( str, substr, 0 ); + p := POSITION_SUBSTRING( str, old, 0 ); if p = fail then return str; fi; @@ -121,10 +118,10 @@ ReplacedString := function ( arg ) pp := 0; while p <> fail do APPEND_LIST_INTR( s, str{[ pp+1 .. p - 1 ]} ); - APPEND_LIST_INTR( s, subs ); + APPEND_LIST_INTR( s, new ); pp := p + lss - 1; if all then - p := POSITION_SUBSTRING( str, substr, pp ); + p := POSITION_SUBSTRING( str, old, pp ); else p := fail; fi; From 70bca27c0a54accc637d7e23a8089126b00f2113 Mon Sep 17 00:00:00 2001 From: Max Horn Date: Mon, 23 Oct 2023 01:20:04 +0200 Subject: [PATCH 2/2] Fix infinite recursion in ReplacedString ... when is empty --- lib/init.g | 6 ++++++ tst/testinstall/strings.tst | 8 ++++++++ 2 files changed, 14 insertions(+) diff --git a/lib/init.g b/lib/init.g index cea842f139..40faba053b 100644 --- a/lib/init.g +++ b/lib/init.g @@ -104,7 +104,13 @@ infinity := "2b defined"; ## ReplacedString := function ( str, old, new, arg... ) local lss, all, p, s, pp; + if old = new then + return str; + fi; lss := LEN_LIST( old ); + if lss = 0 then + Error(" must not be empty"); + fi; if LEN_LIST( arg ) > 0 then all := arg[1] = "all"; else diff --git a/tst/testinstall/strings.tst b/tst/testinstall/strings.tst index d0dd5388b7..84439e4d9a 100644 --- a/tst/testinstall/strings.tst +++ b/tst/testinstall/strings.tst @@ -209,5 +209,13 @@ gap> for len in [10,100,1000,10000,100000] do > Assert(0, Concatenation(str,"\n") = DisplayString(str)); > od;; +# +gap> ReplacedString("Hello world", "Hello", "Goodbye"); +"Goodbye world" +gap> ReplacedString("Hello world", "", ""); +"Hello world" +gap> ReplacedString("Hello world", "", "*"); +Error, must not be empty + # gap> STOP_TEST( "strings.tst", 1);