我有一个元组{' Europe-Fiat-Italy-Warehouse'}。 Car = {' Europe-Fiat-Italy-Warehouse'}。
我想搜索字符串" Fiat"在上面的元组中没有将它们转换为列表中的字符串标记。 即,
(madmax@erlang)46>string:tokens(atom_to_list(element(1, Car)), "-").
["Europe","Fiat","Italy","Warehouse"]
(madmax@erlang)46> ["Europe", "Fiat" | Other] =
string:tokens(atom_to_list(element(1, Car)), "-").
["Europe","Fiat","Italy","Warehouse"]
(madmax@erlang)47>
(madmax@erlang)47> Other.
["Italy","Warehouse"]
(madmax@erlang)48>
如上所述,我们将元组转换为atom,然后将atom转换为list,然后将列表转换为字符串标记。有没有优化的方法?或者erlang中提供的任何Buit-in-Function使这项任务更容易?
答案 0 :(得分:0)
使用string:str
在此处查看文档:{{3}}
它将返回子串的位置,如果未找到子串,则返回零。
string:str(atom_to_list(element(1, Car)), "Fiat")
答案 1 :(得分:0)
内存中原子的表示不使用字符串(或列表),在原子名称中搜索除了首先将其转换为列表之外别无选择。可以使用诸如string:str / 2之类的库函数,但是你可能会得到不好的结果,因为你搜索的字符串可能是较长的字符串的一部分,所以你应该保持对string:token / 2的调用,然后它取决于你想做什么:
1> Car = {'Europe-Fiat-Italy-Warehouse'}.
{'Europe-Fiat-Italy-Warehouse'}
2> Words = string:tokens(atom_to_list(element(1, Car)), "-").
["Europe","Fiat","Italy","Warehouse"]
3> lists:member("Fiat",Words). % only a test
true
4> lists:dropwhile(fun(X) -> "Fiat" =/= X end ,Words). % words after
["Fiat","Italy","Warehouse"]
5> lists:takewhile(fun(X) -> "Fiat" =/= X end ,Words). % words before
["Europe"]
6> lists:member("Fit",Words). % same thing with a bad match
false
7> lists:dropwhile(fun(X) -> "Fit" =/= X end ,Words).
[]
8> lists:takewhile(fun(X) -> "Fit" =/= X end ,Words).
["Europe","Fiat","Italy","Warehouse"]
9>