如何在Erlang中从列表或字符串中删除字符?

myss37ts  于 2022-12-08  发布在  Erlang
关注(0)|答案(2)|浏览(189)

如何从列表中删除字符/(或称之为字符串)

List = "/hi"
jucafojl

jucafojl1#

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.

wljmcqd8

wljmcqd82#

因为Erlang变量是不可变的,

List = "/hi".

List绑定到表达式"\hi",则不能简单地从List中删除任何内容;实际上,只要List保持绑定状态,就不能以任何方式对其进行更改。
你可以把另一个变量T绑定到List的尾部,如下所示:

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

相关问题