恶狼传说[erlang字符串模拟php]

看着Erlang字符串操作不尽如人意,何不试着模拟实现php的字符串一些基本的操作?

最近又有点时间玩Erlang了,顺手先写下两个,有空再完善。

-module(mystring).
-export([strpos/2
,substr/2
,substr/3
,trim/1
,replace/3
,replace/4
,strstr/2
,strbef/2
,parse_str/1
,addslashes/1]).

%Function->[strpos]
%Get first location of character/string
%did not use any algorithm like kmp or sunday(should be improved later)
strpos(S,C) -> strpos(S,C,0).
strpos([H|T],[CH|CT],SS) ->
case CH == H of
true -> find([H|T],[CH|CT],[CH|CT],SS);
false -> strpos(T,[CH|CT],SS+1)
end;
strpos([],_,_) -> -1.
find([TH|TT],[FH|FT],C,TF) ->
case TH == FH of
true -> find(TT,FT,C,TF);
false -> strpos(TT,C,TF+1)
end;
find([],[],_,TF) -> TF;
find([],_,_,_) -> -1;
find(_,[],_,TF) -> TF.

%Function->[substr]
%Get part of stirng,different from string:sub_string
substr(S,P) -> ssubstr(S,P,0).
ssubstr([SH|ST],P,L) ->
case L == P of
true -> [SH|ST];
false -> ssubstr(ST,P,L+1)
end;
ssubstr([],_,_) -> [].

substr(S,P,E) -> substr(S,P,E,0,[]).
substr([SH|ST],P,E,L,C) ->
if
E == 0 -> [];
L == P -> substr(ST,P,E,L+1,[SH|C]);
L == E+P -> lists:reverse(C);
C == [] -> substr(ST,P,E,L+1,C);
true -> substr(ST,P,E,L+1,[SH|C])
end;
substr([],_,_,_,C) -> lists:reverse(C).

%Function->[trim]
%Strip space at beginning or end of string.
%trim(S) -> lists:reverse(ltrim(lists:reverse(ltrim(S)))).
%ltrim([H|T]) ->
% case [H] == " " of
% true -> ltrim(T);
% false -> [H|T]
% end.
trim(S) -> string:strip(S,both,32).

%Function->[replace]
%Replace all/specific occurrences of `T` whith `R`
replace(S,T,R) -> replace(S,T,R,all).
replace(S,T,R,C) ->
L = string:len(T),
P = strpos(S,T),
replace(S,T,R,P,L,C).
replace(S,T,R,P,L,C) ->
NS = substr(S,0,P) ++ R,
NP = substr(S,P+L),
if
%We don't found the sub string
P == -1 -> S;
%Wanna replace all?
C == all -> NS ++ replace(NP,T,R);
C == 0 -> S;
%Do specific times replacement.
true -> NS ++ replace(NP,T,R,C-1)
end.

%Function->[strstr]
%Get subsequent charaters with the first occurence charater/string
strstr(S,T) -> N = strpos(S,T),substr(S,N).
strbef(S,T) -> N = strpos(S,T),substr(S,0,N).

%Function->[parse_str]
%Parse query sting in url
parse_str(S) -> parse_str2(string:tokens(S,"&")).
%%%%ugly implement below.
% FA = strbef([T|H],"&"),
% FS = string:tokens(FA,"="),
% SQ = strstr([T|H],"&"),
% case SQ == [] of
% true -> [FS];
% false -> [FS|parse_str(substr(SQ,1))]
% end;
%parse_str([]) -> [].
%%%ugly implement end.
parse_str2([H|T]) -> [string:tokens(H,"=")|parse_str2(T)];
parse_str2([]) -> [].

 

运行结果。

posted @ 2012-03-05 00:05  一缕青烟  阅读(858)  评论(1编辑  收藏  举报