herd_string.erl 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. -module(herd_string).
  2. -export([fill_before/3, split/2, replace/3,
  3. escape_xml/1, escape_json/1]).
  4. %%% module API
  5. -spec fill_before(string(), char(), integer()) -> string().
  6. fill_before(Str, Char, ToLength) ->
  7. case length(Str) of
  8. Length when Length >= ToLength -> Str;
  9. _ -> fill_before([Char | Str], Char, ToLength)
  10. end.
  11. -spec split(string(), string()) -> [string()].
  12. split("", _) -> "";
  13. split(Str, "") -> [Str];
  14. split(Str, WithStr) -> split(Str, WithStr, [], []).
  15. -spec split(string(), string(), [char()], [string()]) -> [string()].
  16. split([], _, [], Acc2) -> lists:reverse(Acc2);
  17. split([], _, Acc1, Acc2) -> lists:reverse([lists:reverse(Acc1) | Acc2]);
  18. split(Str, WithStr, Acc1, Acc2) ->
  19. io:format("~p ~p ~p ~p", [Str, WithStr, Acc1, Acc2]),
  20. case lists:prefix(WithStr, Str) of
  21. true -> Str2 = lists:sublist(Str, length(WithStr) + 1, length(Str)),
  22. case Acc1 of
  23. [] -> split(Str2, WithStr, [], Acc2);
  24. _ -> split(Str2, WithStr, [], [lists:reverse(Acc1) | Acc2])
  25. end;
  26. false -> [Char | Str2] = Str,
  27. split(Str2, WithStr, [Char | Acc1], Acc2)
  28. end.
  29. -spec replace(string(), string(), string()) -> string().
  30. replace([], _, _) -> "";
  31. replace(Str, Old, New) ->
  32. case lists:prefix(Old, Str) of
  33. true -> Str2 = lists:sublist(Str, length(Old) + 1, length(Str)),
  34. New ++ replace(Str2, Old, New);
  35. false -> [Char | Str2] = Str,
  36. [Char | replace(Str2, Old, New)]
  37. end.
  38. -spec escape_xml(string()) -> string().
  39. escape_xml(Str) ->
  40. lists:flatten(
  41. lists:map(fun($&) -> "&";
  42. ($>) -> ">";
  43. ($<) -> "&lt;";
  44. ($") -> "&quot;";
  45. (Char) -> Char
  46. end, Str)).
  47. -spec escape_json(string()) -> string().
  48. escape_json(Str) ->
  49. lists:flatten(
  50. lists:map(fun(92) -> "\\\\";
  51. (34) -> "\\\"";
  52. (10) -> "\\n";
  53. (13) -> "\\r";
  54. (9) -> "\\t";
  55. (Char) -> Char
  56. end, Str)).