Search code examples
stringprologsubstringswi-prolog

Ask the user to input two strings and check whether one string is a substring of another in prolog


I'm new to prolog. I just wrote some code. Can you please help me out with this question. Thank you.

My Code:

write('Enter the first string:'), nl, 
write('Enter the second string:'), nl.

How to proceed from here ?


Solution

  • run rule will drive the experiment.. .pl file

    substring(X,S) :-
        string_to_list(X, XL),
        string_to_list(S, SL),
        append(_,T,SL) ,
        append(XL,_,T) ,
        X \= [], !.
        
    % example
    % ?- substring("aa", "abaa").
    %   true.
    % ?- substring("aa", "ababa").
    %   false.
    
    run :- write('Enter the first string: '), read(Str1), nl, write('Enter the second string: '), read(Str2), nl,
            (substring(Str1, Str2) -> format('~w is contained in ~w', [Str1, Str2]); format('~w is not in ~w', [Str1, Str2])).
            
    % example
    % ?- run.
    

    Usage..

    enter image description here