看到论坛上大家在讨论阿里的程序题:字符串的处理问题,逆转,如"www.baidu.com"变为"com.baidu.www",就手痒用erlang写了一个,不过写的很丑很低效。
1 -module(my_reverse).
2 -export([this_reverse/1,this_split/2]).
3
4 this_reverse(L) ->
5 binary_to_list(this_reverse([],[],L)).
6 this_reverse(H,TP,T) ->
7 case get_head(T) of
8 {$., T1} ->
9 this_reverse([".",lists:reverse(TP)|H], [], T1);
10 {H1,[]} ->
11 %[lists:reverse([H1|TP])|H];
12 list_to_binary([lists:reverse([H1|TP])|H]);
13 {H1, T1} ->
14 this_reverse(H, [H1|TP], T1)
15 end.
16
17 get_head(L) ->
18 [H|T]=L,
19 {H, T}.
20
21 this_split(L, M) ->
22 this_split([],[],L, M).
23 this_split(H, TP, L, M) ->
24 case get_head(L) of
25 {M, T1} ->
26 this_split([TP|H], [], T1, M);
27 {H1, []}->
28 [[H1|TP]|H];
29 {H1, T1}->
30 this_split(H, [H1|TP], T1, M)
31 end.
my_reverse是翻转函数,然后顺手写了个字符串任意分隔函数。
总觉得还是正则表达式来搞匹配要容易的多啊。