【发布时间】:2020-01-11 10:08:33
【问题描述】:
为了替换字符串中的子字符串,我写了一个谓词replace_substring。它使用 SWI-Prolog 的 append/3 谓词:
:- 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 是否具有可用于相同目的的内置谓词?
【问题讨论】:
-
你对
replace_substring("aa","a","b", R)有什么期望? -
replace_substring("abc", "bc", "23", R).会成功,但replace_substring("abc", "b", "2", R).会失败,因为只有当被替换的子字符串是原始字符串的后缀时,您的实现才会成功。