Reputation: 21
I am a beginner to prolog. How can I convert letters into * (asterisk)? I know that it is a character codes in prolog to represent strings. The problem is if it is a letter, convert it to " *", if it is a underscore, just keep it.
So how do I know whether it is a underscore or not?
Upvotes: 2
Views: 384
Reputation: 21990
So, the task is to replace letters with asterisks. At first, you should google some material about strings in prolog. Than it's easy to have something like that
string_replace( [], [] ).
string_replace( [H | Tail], StringNew ) :-
( not(underscore(H)), asterisk(A), StringNew = [A | StringTail], string_replace( Tail, StringTail) )
;
( underscore(H), StringNew = [H | StringTail], string_replace( Tail, StringTail) )
.
letter( X ) :-
( X >= 97, X =< 122 )
;
( X >=65, X =<90 ).
underscore( 95 ).
asterisk( 42 ).
main :-
string_replace( "test_string", S1 ),
writef( "%s", [S1] ), nl,
string_replace( "another string", S2 ),
writef( "%s", [S2] ), nl,
!
.
It works like that
?- main.
****_******
**************
true.
It don't use any builtins predicates, but it's could be useful to understand how all it really works.
Upvotes: 1
Reputation: 60034
check each character in string:
...maplist(convstar, String, Converted), ...
convstar(0'_, 0'_).
convstar(_, 0'*).
Another way, using an 'if-then' construct:
convstar(X, Y) :-
( X == 0'_
-> Y = 0'_
; Y = 0'*
).
Upvotes: 0