Reputation: 456
I'm doing an assignment in Prolog (I'm a newbie) and I have a small problem. I know you can split a string to a list of elements in Prolog like this:
split_string("Hello, here I am!"," "," .!?-_'",Temp).
But this takes out the basic punctuation. It returns:
Temp = ['Hello','here','I','am'].
How can I change it in order to keep the punctuation like this:
Temp = ['Hello',',','here','I','am','!'].
Thank you in advance for your help!
Upvotes: 0
Views: 406
Reputation: 3529
"split_string" is not standard but, in the implementation I know, you can not. From the ECLIPSe manual:
The string String is split at the separators, and any padding characters around the resulting sub-strings are removed. Neither the separators nor the padding characters occur in SubStrings.
** Addendum **
We can play a few with string functions to recover the "list" separators:
split_with_delimiters(String,Delimiters,Ignore,Result) :-
split_string(String,Delimiters,"",FirstSplit),
split_with_delimiters_aux(Ignore,String,FirstSplit,Result).
split_with_delimiters_aux(_,"",_,[]) :- !.
split_with_delimiters_aux(Ignore,String,[""|Q],Result) :- !,
split_with_delimiters_aux(Ignore,String,Q,Result).
split_with_delimiters_aux(Ignore,String,[H|Q],[H|Result]) :-
string_concat( H, Rest, String ), !,
split_with_delimiters_aux(Ignore,Rest,Q,Result).
split_with_delimiters_aux(Ignore,String,Split,Result) :-
sub_string( String, 0, 1, RestL, Delimiter ),
sub_string( String, 1, RestL, _, Rest ),
sub_string( Delimiter, _, _, _, Ignore ), !,
split_with_delimiters_aux(Ignore,Rest,Split,Result).
split_with_delimiters_aux(Ignore,String,Split,[Delimiter|Result]) :-
sub_string( String, 0, 1, RestL, Delimiter ),
sub_string( String, 1, RestL, _, Rest ),
split_with_delimiters_aux( Ignore,Rest, Split, Result ).
that provides following result:
?- split_with_delimiters("Hello, here I am!"," ,.!?-_'"," ",Res).
Res = ["Hello", ",", "here", "I", "am", "!"]
(things could be easier if we convert string to/from list at start/end)
Upvotes: 1