Reputation: 395
Premise
So I'm trying to break up a given String into a list of characters, these characters will then be edited/changed and reassigned into the list after which the list will be reconstructed back into a String.
An example:
Given String : "ABCDEFG"
Character list : [A,B,C,D,E,F,G]
Operation changes the list to something like the following: [E,F,G,H,I,J,K] (Or something similar).
And then gets reconstructed into a String:
"EFGHIJK"
Question
I am looking for a way to access individual elements inside of a String. If it were Java I would use a command like charAt(int i)
but I don't know if such a command exists within prolog.
Note
I am a new prolog
programmer so I'm not familiar with most prolog
operations.
Thanks for your time.
Upvotes: 4
Views: 5466
Reputation: 60014
A string it's a list of char codes, while an atom it's, well, atomic, i.e. indivisible, but there is sub_atom/5 to access parts of the atomic data.
Here some string example:
1 ?- L = "ABCDEF".
L = [65, 66, 67, 68, 69, 70].
2 ?- L = "ABCDEF", maplist(succ, L, N), format('~s', [N]).
BCDEFG
L = [65, 66, 67, 68, 69, 70],
N = [66, 67, 68, 69, 70, 71].
3 ?- L = "ABCDEF", maplist(succ, L, N), format('~s', [N]), atom_codes(A, N).
BCDEFG
L = [65, 66, 67, 68, 69, 70],
N = [66, 67, 68, 69, 70, 71],
A = 'BCDEFG'.
If the analysis and transformation require detail then usually it's better to use DCGs
Upvotes: 3
Reputation: 5675
You can try this
t(S_in, S_out) :-
maplist(modif, S_in, S_temp),
string_to_list(S_out, S_temp).
modif(In, Out) :-
atom_codes('A', [X]),
atom_codes('E', [Y]),
Out is In + Y - X.
A string is a list of codes in Prolog. So maplist applies a modification on each codes of the list (a funtionnal way). string_to_list is usefull to get a string at the output instead of a list of codes.
You can write modif in a quickly way but I wrote it in the way you can understand it easily.
The output is
?- t("ABCDEFG", Out).
Out = "EFGHIJK".
Upvotes: 1
Reputation: 143
Strings are atoms in Prolog.
In your case you may do something like this: "EFGHIJK" = List.
Here's a good post about it: http://obvcode.blogspot.com/2008/11/working-with-strings-in-prolog.html
Upvotes: 1