问题
I need to get the last char of a string. For example:
?- last_char('abde', X).
X = 'e'
?- last_char('abdef', X).
X = 'f'
Could someone help me, please? I'm new to Prolog.
回答1:
with a little help from sub_atom/5, a really handy ISO builtin:
?- sub_atom(abdef, _, 1, 0, C).
C = f.
回答2:
You could use name and reverse to convert the string to a list and back:
last_char(S, X) :-
name(S, N),
reverse(N, [F|_]),
name(X, [F]).
Depending on your Prolog version you might have to import a list library for the reverse predicate, e.g. :- use_module(library(lists)). for SICStus.
来源:https://stackoverflow.com/questions/19734799/getting-last-char-of-a-string-in-prolog