4
votes

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.

3

3 Answers

3
votes

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

1
votes

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

1
votes

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".