Availability:built-in
Pick out a sub-atom of length 3 starting a 0-based index 2:
?- sub_atom(aaxyzbbb, 2, 3, After, SubAtom). After = 3, SubAtom = xyz.
The following example splits a string of the form <name>=<value> into the name part (an atom) and the value (a string).
name_value(String, Name, Value) :- sub_atom(String, Before, _, After, "="), !, sub_atom(String, 0, Before, _, Name), sub_atom(String, _, After, 0, Value).
This example defines a predicate that inserts a value at a position. Note that sub_string/5 is used here instead of sub_atom/5 to avoid the overhead of creating atoms for the intermediate results.
atom_insert(Str, Val, At, NewStr) :- sub_string(Str, 0, At, A1, S1), sub_string(Str, At, A1, _, S2), atomic_list_concat([S1,Val,S2], NewStr).
On backtracking, matches are delivered in order left-to-right (i.e. Before increases monotonically):
?- sub_atom('xATGATGAxATGAxATGAx', Before, Length, After, 'ATGA'). Before = 1, Length = 4, After = 14 ; Before = Length, Length = 4, After = 11 ; Before = 9, Length = 4, After = 6 ; Before = 14, Length = 4, After = 1 ; false.
See also sub_string/5, the corresponding predicate for SWI-Prolog strings.