Rui Motta
Rui Motta

Reputation: 141

How to replace a character in a string in Erlang?

I want to check if a string contains a specific character ("*") and if so, I want to replace it with another character ("%").

Like this: String = "John*"

Changes to: String = "John%"

Thank you

Upvotes: 1

Views: 2797

Answers (2)

2240
2240

Reputation: 1710

1> io:format(string:replace("John*", "*", "%")).
John%ok

You can use string:replace/3.

Upvotes: 1

Hynek -Pichi- Vychodil
Hynek -Pichi- Vychodil

Reputation: 26121

Straightforward:

-module(replace).

-export([replace/3]).

replace([], _, _) -> [];
replace([H|T], P, R) ->
    [ if H =:= P -> R;
         true -> H
      end | replace(T, P, R)].

Usage:

$ erl
Erlang/OTP 20 [erts-9.3] [source] [64-bit] [smp:4:4] [ds:4:4:10] [async-threads:10] [hipe] [kernel-poll:false]

Eshell V9.3  (abort with ^G)
1> c(replace).
{ok,replace}
2> replace:replace("John*", $*, $%).
"John%"

Upvotes: 3

Related Questions