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:
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:
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:
2条答案
按热度按时间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:
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:
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: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 resultSegments
is a list of strings, which we now need to join back together. We can use eitherlists:flatten/1
orstring:join/2
for that:The second argument to
string:join/2
is a separator you can insert between segments, but here, we just use the empty string.wljmcqd82#
因为Erlang变量是不可变的,
将
List
绑定到表达式"\hi"
,则不能简单地从List
中删除任何内容;实际上,只要List
保持绑定状态,就不能以任何方式对其进行更改。你可以把另一个变量
T
绑定到List
的尾部,如下所示: