# String Processing

**URL:** <https://swi-prolog.discourse.group/t/string-processing/3286>\
**Category:** Help!\
**Created:** [November 20, 2020, 5:14pm UTC](https://swi-prolog.discourse.group/t/string-processing/3286 "2020-11-20T17:14:11Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![PrologAxel](https://avatars.discourse-cdn.com/v4/letter/p/ad7895/32.png) [@PrologAxel](https://swi-prolog.discourse.group/u/PrologAxel)\
**Post date:** [November 20, 2020, 5:14pm UTC](https://swi-prolog.discourse.group/t/string-processing/3286/1 "2020-11-20T17:14:11Z")

</div>

I’m using: SWI-Prolog version 8.2.1

Hello.

In Java it is very easy:

```java
String word = "asdHulofasdFado"

```

for-loop goes through an array:

```
the word gets manipulated by every entry of the array .. In prolog it would be a list.

first entry of array: Hulu Muba ..So replace hulo by Muba
Result: asdMubafasdFado

second entry of array: Fado Gedi
Result: asdMubafasdGedi

So every entry changes the word.

```

End for-loop.

The only problem I have is the variable word.  
Somewhere I have to save it, so I can manipulate it.

I only know two methods: Traverse a List and loop

```prolog
goThroughList([], []).
goThroughList([V|R], Z) :- 
   goThroughList(R, D),
   something(V, K),
   append(D,[K],Z).

```

And

```prolog
loop(N, A , L) :- 
   ...,
   loop(S, A ,R).

```

Both do not help to solve the problem. Because I cannot transfer the variable word.

Thank you

---

<div class="post-metadata">

**Author:** ![Boris](https://yyz2.discourse-cdn.com/free1/user_avatar/swi-prolog.discourse.group/boris/32/7486_2.png) [@Boris](https://swi-prolog.discourse.group/u/Boris)\
**Post date:** [November 20, 2020, 5:47pm UTC](https://swi-prolog.discourse.group/t/string-processing/3286/2 "2020-11-20T17:47:49Z")

</div>

You don’t need append. You need an accumulator:

```prolog
replace_all([], R, R).
replace_all([Pattern-With|Rest], S, R) :-
    re_replace(Pattern/g, With, S, R0),
    replace_all(Rest, R0, R).

```

You could also use foldl. Like this:

```prolog
replace_all(Replacements, String, Result) :-
    foldl(replace, Replacements, String, Result).

replace(Pattern-With, String, Result) :-
    re_replace(Pattern/g, With, String, Result).

```

```prolog
?- replace_all(["Hulo"-"Muba", "Fado"-"Gedi"], "asdHulofasdFado", Result).
Result = "asdMubafasdGedi".

```

---

<div class="post-metadata">

**Author:** ![PrologAxel](https://avatars.discourse-cdn.com/v4/letter/p/ad7895/32.png) [@PrologAxel](https://swi-prolog.discourse.group/u/PrologAxel)\
**Post date:** [November 20, 2020, 6:20pm UTC](https://swi-prolog.discourse.group/t/string-processing/3286/3 "2020-11-20T18:20:12Z")

</div>

Thank you. It solved the problem perfectly. Never heard of foldl before.
