从 Prolog 中的字符串替换第 n 个子字符串
Replacing nth substring occurrence from a String in Prolog
我正在尝试创建一个谓词来替换字符串中出现的第 n 个子字符串。
replace_word(word, nthOcurrence, toReplace, replaceWith , Result)
所以如果我调用 replace_word(zXyyyzXyyXzX, 2, zX, OO , Result)
我可以获得
Result = zXyyyOOyyXzX
我尝试实现这个实用程序
replace_word(Old, New, Orig, Replaced) :-
atomic_list_concat(Split, Old, Orig),
atomic_list_concat(Split, New, Replaced).
但它取代了所有出现。
欢迎任何提示。谢谢!
最近添加的 call_nth/2, together with the flexible ISO predicate sub_atom/5,允许干净的实现:
replace_nth_word(Word,NthOcurrence,ToReplace,ReplaceWith,Result) :-
call_nth(sub_atom(Word,Before,_Len,After,ToReplace),NthOcurrence),
sub_atom(Word,0,Before,_,Left), % get left part
sub_atom(Word,_,After,0,Right), % get right part
atomic_list_concat([Left,ReplaceWith,Right],Result).
显然,它也适用于 字符串 ,这要归功于从版本 7 开始在 SWI-Prolog 中实现的文字扩展表示。
我正在尝试创建一个谓词来替换字符串中出现的第 n 个子字符串。
replace_word(word, nthOcurrence, toReplace, replaceWith , Result)
所以如果我调用 replace_word(zXyyyzXyyXzX, 2, zX, OO , Result)
我可以获得
Result = zXyyyOOyyXzX
我尝试实现这个实用程序
replace_word(Old, New, Orig, Replaced) :-
atomic_list_concat(Split, Old, Orig),
atomic_list_concat(Split, New, Replaced).
但它取代了所有出现。 欢迎任何提示。谢谢!
最近添加的 call_nth/2, together with the flexible ISO predicate sub_atom/5,允许干净的实现:
replace_nth_word(Word,NthOcurrence,ToReplace,ReplaceWith,Result) :-
call_nth(sub_atom(Word,Before,_Len,After,ToReplace),NthOcurrence),
sub_atom(Word,0,Before,_,Left), % get left part
sub_atom(Word,_,After,0,Right), % get right part
atomic_list_concat([Left,ReplaceWith,Right],Result).
显然,它也适用于 字符串 ,这要归功于从版本 7 开始在 SWI-Prolog 中实现的文字扩展表示。