检查字符串是否在Prolog中是子字符串 [英] Check if string is substring in Prolog

查看:168
本文介绍了检查字符串是否在Prolog中是子字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有一种方法可以检查一个字符串是否是Prolog中另一个字符串的子字符串?我尝试将字符串转换为字符列表,然后检查第一个字符集是否是第二个字符集的子集,而该子集似乎不够严格.这是我当前的代码:

Is there a way to check if a string is a substring of another string in Prolog? I tried converting the string to a list of chars and subsequently checking if the first set is a subset of the second that that doesn't seem to be restrictive enough. This is my current code:

isSubstring(X,Y):-
        stringToLower(X,XLower),
        stringToLower(Y,YLower),
        isSubset(XLower,YLower).

isSubset([],_).
isSubset([H|T],Y):-
        member(H,Y),
        select(H,Y,Z),
        isSubset(T,Z).

stringToLower([],[]).
stringToLower([Char1|Rest1],[Char2|Rest2]):-
        char_type(Char2,to_lower(Char1)),
        stringToLower(Rest1,Rest2).

如果我对此进行测试

isSubstring("test","tesZting").

isSubstring("test","tesZting").

它返回是,但应该返回否.

it returns yes, but should return no.

推荐答案

序言字符串是列表,其中列表的每个元素都是代表所讨论字符的代码点的整数值.字符串"abc"与列表[97,98,99] 完全等效(假设您的序言实现使用的是Unicode或ASCII,否则值可能会有所不同).这就导致了这个解决方案(从Big-O的角度来看可能不是最理想的),该解决方案基本上说X是S if的子字符串.

Prolog strings are lists, where each element of the list is the integer value representing the codepoint of the character in question. The string "abc" is exactly equivalent to the list [97,98,99] (assuming your prolog implementation is using Unicode or ASCII, otherwise the values might differ). That leads to this (probably suboptimal from a Big-O perspective) solution, which basically says that X is a substring of S if

  • S的后缀T如此,
  • X是T的前缀

代码如下:

substring(X,S) :-
  append(_,T,S) ,
  append(X,_,T) ,
  X \= []
  .

我们将X限制为空列表(也称为nil字符串"")以外的其他内容,因为从概念上讲,它可以在任何字符串中找到很多零长度子字符串:长度为 n <的字符串/em>具有2 +( n -1)个nil子字符串,在字符串的每个字符之间一个,在第一个字符之前,在最后一个字符之后.

We restrict X to being something other than the empty list (aka the nil string ""), since one could conceptually find an awful lot of zero-length substrings in any string: a string of length n has 2+(n-1) nil substrings, one between each character in the string, one preceding the first character and one following the last character.

这篇关于检查字符串是否在Prolog中是子字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆