Replace 在Prolog中替换子字符串

Replace 在Prolog中替换子字符串,replace,prolog,Replace,Prolog,为了替换字符串中的子字符串,我编写了一个名为replace\u substring的谓词。它使用SWI Prolog的谓词: :- initialization(main). :- set_prolog_flag(double_quotes, chars). main :- replace_substring("this is a string","string","replaced string",Result), writeln(Result). replace_sub

为了替换字符串中的子字符串,我编写了一个名为
replace\u substring
的谓词。它使用SWI Prolog的谓词:

:- initialization(main).
:- set_prolog_flag(double_quotes, chars). 

main :-
    replace_substring("this is a string","string","replaced string",Result),
    writeln(Result).

replace_substring(String,To_Replace,Replace_With,Result) :-
    append(First,To_Replace,String),
    append(First,Replace_With,Result).

不过,我不确定这是否是替换Prolog中的子字符串的最有效方法。Prolog是否有一个可用于相同目的的内置谓词?

简短的回答是,否,Prolog没有内置的字符串替换谓词。仅当子字符串位于原始字符串的末尾时,显示的内容才会替换该子字符串。也就是说,它将替换字符串
“xyzabc”
中的
“abc”
,而不是字符串
“xyabcz”
中的

您可以使用
append/2

replace_substring(String, To_Replace, Replace_With, Result) :-
    append([Front, To_Replace, Back], String),
    append([Front, Replace_With, Back], Result).
如果希望在不匹配的情况下成功替换,则:

replace_substring(String, To_Replace, Replace_With, Result) :-
    (    append([Front, To_Replace, Back], String)
    ->   append([Front, Replace_With, Back], Result)
    ;    Result = String
    ).
正如他的问题中的@false提示,您是否要处理替换多个事件?如果是这样,您的方法的扩展将是:

replace_substring(String, To_Replace, Replace_With, Result) :-
    (    append([Front, To_Replace, Back], String)
    ->   append([Front, Replace_With, Back], R),
         replace_substring(Back, To_Replace, Replace_With, Result)
    ;    Result = String
    ).

您对替换子字符串(“aa”、“a”、“b”、“R”)有何期望?
替换子字符串(“abc”、“bc”、“23”、“R”)
将成功,但
替换子字符串(“abc”、“b”、“2”、“R”).
将失败,因为只有当替换的子字符串是原始字符串的后缀时,您的实现才会成功。这将使所有子字符串都成为非关系字符串。。。