ocaml/ocaml — pull request #10 by dbuenzli (2014-02-14 16:35:36+00:00)
Title: Add String.split.

I recently cut and pasted in (library) code a restricted version of `String.split` at least trice (well maybe if we didn't get stacktraces as strings I wouldn't need it...). Since I see `String.trim` was introduced in 4.00.0. I'm tempted to propose this one.

Below you'll find the behaviour of `String.split` on a few edge cases. It should be noted that it coincides with the behaviour of `Str.(split_delim (regexp str) s)` except on a few cases (see the `Str =` comments). On these cases I think that what `String.split` does is better behaved and more regular since what `Str.split_delim` does is not captured by the simple textual specification of `String.split` I give in the documentation which is:

```
[String.split sep s] is the list of all (possibly empty) substrings of [s]
that are separated by [sep]. If there is no [sep] in [s], [[s]] is returned.
The invariant [String.concat sep (String.split sep s) = s] always holds.
```

```ocaml
let () =
assert (String.split "" "" = [""; ""]);
(* Str = [] *)
assert (String.split "" "123" = [""; "1"; "2"; "3"; ""]);
(* Str = ["1"; "2"; "3"; ""] *)
assert (String.split "," "" = [""]);
(* Str = [] *)
assert (String.split "," "," = [""; ""]);
assert (String.split "," ",," = [""; ""; ""]);
assert (String.split "," ",,," = [""; ""; ""; ""]);
assert (String.split "," "123" = ["123"]);
assert (String.split "," ",123" = [""; "123"]);
assert (String.split "," "123," = ["123"; ""]);
assert (String.split "," "1,2,3" = ["1"; "2"; "3"]);
assert (String.split "," "1, 2, 3" = ["1"; " 2"; " 3"]);
assert (String.split "," ",1,2,,3," = [""; "1"; "2"; ""; "3"; ""]);
assert (String.split "," ", 1, 2,, 3," = [""; " 1"; " 2"; ""; " 3"; ""]);
assert (String.split "<>" "" = [""]);
(* Str = [] *)
assert (String.split "<>" "<>" = [""; ""]);
assert (String.split "<>" "<><>" = [""; ""; ""]);
assert (String.split "<>" "<><><>" = [""; ""; ""; ""]);
assert (String.split "<>" "123" = [ "123" ]);
assert (String.split "<>" "<>123" = [""; "123"]);
assert (String.split "<>" "123<>" = ["123"; ""]);
assert (String.split "<>" "1<>2<>3" = ["1"; "2"; "3"]);
assert (String.split "<>" "1<> 2<> 3" = ["1"; " 2"; " 3"]);
assert (String.split "<>" "<>1<>2<><>3<>" = [""; "1"; "2"; ""; "3"; ""]);
assert (String.split "<>" "<> 1<> 2<><> 3<>" = [""; " 1"; " 2"; ""; " 3";""]);
assert (String.split "<>" ">>><>>>><>>>><>>>>" =
[">>>"; ">>>"; ">>>"; ">>>" ]);
assert (String.split "<->" "<->>->" = [""; ">->"]);
()
```