Is it possible in prolog to replace all white spaces of a string with some given character?
Example-
If I have a variable How are you today?
and I want How_are_you_today?
There are may ways in which this can be done. I find the following particularly simple, using atomic_list_concat/3
:
?- atomic_list_concat(Words, ' ', 'How are you today?'), atomic_list_concat(Words, '_', Result).
Words = ['How', are, you, 'today?'],
Result = 'How_are_you_today?'.
The above can also be done with SWI strings. Unfortunately, there is no string_list_concat/3
which would have made the conversion trivial. split_string/4
is very versatile, but it only does half of the job:
?- split_string("How are you today?", " ", "", Words).
Words = ["How", "are", "you", "today?"].
We can either define string_list_concat/3
ourselves (a first attempt at defining this is shown below) or we need a slightly different approach, e.g. repeated string_concat/3
.
string_list_concat(Strings, Separator, String):-
var(String), !,
maplist(atom_string, [Separator0|Atoms], [Separator|Strings]),
atomic_list_concat(Atoms, Separator0, Atom),
atom_string(Atom, String).
string_list_concat(Strings, Separator, String):-
maplist(atom_string, [Separator0,Atom], [Separator,String]),
atomic_list_concat(Atoms, Separator0, Atom),
maplist(atom_string, Atoms, Strings).
And then:
?- string_list_concat(Words, " ", "How are you today?"), string_list_concat(Words, "_", Result).
Words = ["How", "are", "you", "today?"],
Result = "How_are_you_today?".