emzemzx
emzemzx

Reputation: 165

How do I remove a character from a list or string in Erlang?

How do I remove the character / from this list (or call it a string)

List = "/hi"

Upvotes: 3

Views: 2868

Answers (2)

jub0bs
jub0bs

Reputation: 66422

Because Erlang variables are immutable and

List = "/hi".

binds List to the expression "\hi", you cannot simply remove anything from List; in fact, you cannot alter List in any way as long as it remains bound.

What you can do instead is bind another variable, called T below, to the tail of List, like so:

1> List = "/hi".
"/hi"
2> T=tl(List).
"/hi"
3> T.
"hi"

Upvotes: 5

Steve Vinoski
Steve Vinoski

Reputation: 20024

Since strings in Erlang are lists of characters, a general way to delete the first occurrence of a character from a string is to use lists:delete/2:

1> List = "/hi".
"/hi"
2> lists:delete($/, List).
"hi"

The construct $/ is the Erlang character literal for the / character.

Note that this approach works no matter where the character to be deleted is within the string:

3> List2 = "one/word".
"one/word"
4> lists:delete($/, List2).
"oneword"

Just remember that with this approach, only the first occurrence of the character is deleted. To delete all occurrences, first use string:tokens/2 to split the entire string on the given character:

5> List3 = "/this/looks/like/a/long/pathname".
"/this/looks/like/a/long/pathname"
6> Segments = string:tokens(List3, "/").
["this","looks","like","a","long","pathname"]

Note that string:tokens/2 takes its separator as a list, not just a single element, so this time our separator is "/" (or equivalently, [$/]). Our result Segments is a list of strings, which we now need to join back together. We can use either lists:flatten/1 or string:join/2 for that:

7> lists:flatten(Segments).
"thislookslikealongpathname"
8> string:join(Segments, "").
"thislookslikealongpathname"

The second argument to string:join/2 is a separator you can insert between segments, but here, we just use the empty string.

Upvotes: 7

Related Questions