本文介绍了替换 Prolog 中的子串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为了替换字符串中的子字符串,我写了一个谓词,叫做replace_substring.它使用 SWI-Prolog 的 append/3 谓词:>

In order to replace a substring in a string, I wrote a predicate called replace_substring. It uses SWI-Prolog's append/3 predicate:

:- 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 是否具有可用于相同目的的内置谓词?

Still, I'm not sure if this is the most efficient way to replace substrings in Prolog. Does Prolog have a built-in predicate that could be used for the same purpose?

推荐答案

简短的回答是,不,Prolog 没有内置的字符串替换谓词.如果该子字符串位于原始字符串的末尾,则您显示的内容只会替换该子字符串.也就是说,它将替换字符串 "xyzabc" 中的 "abc" 而不是字符串 "xyabcz" 中的 .

The short answer is, no, Prolog does not have a built-in string replace predicate. What you show will only replace the substring if that substring is at the end of the original string. That is, it will replace "abc" in the string "xyzabc" but not in the string "xyabcz".

你可以使用append/2:

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

如果您希望它在不替换不匹配的情况下成功,则:

If you want it to succeed without replacing on a non-match, then:

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

正如@false 在他的问题中所暗示的那样,您要处理替换多次出现吗?如果是这样,您的方法的扩展将是:

As @false hints in his question, do you want to handle replacing multiple occurrences? If so, the extension to your method would be:

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
    ).

这篇关于替换 Prolog 中的子串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-13 06:07