String.split

master
alainfrisch 2016-06-20 11:36:42 +02:00
parent bd9d5555b6
commit 4c979b80a8
3 changed files with 41 additions and 0 deletions

View File

@ -127,6 +127,17 @@ type t = string
let compare (x: t) (y: t) = Pervasives.compare x y
external equal : string -> string -> bool = "caml_string_equal"
let split sep s =
let r = ref [] in
let j = ref (length s) in
for i = length s - 1 downto 0 do
if unsafe_get s i = sep then begin
r := sub s (i + 1) (!j - i - 1) :: !r;
j := i
end
done;
sub s 0 !j :: !r
(* Deprecated functions implemented via other deprecated functions *)
[@@@ocaml.warning "-3"]
let uppercase s =

View File

@ -282,6 +282,21 @@ val equal: t -> t -> bool
(** The equal function for strings.
@since 4.03.0 *)
val split: char -> string -> string list
(** [String.split sep s] returns the list of all (possibly empty)
substrings of [s] that are delimited by the [sep] character.
The function's output is specified by the following invariants:
- The list is not empty.
- Concatenating its elements using [sep] as a separator returns a
string equal to the input ([String.concat (String.make 1 sep)
(String.split sep s) = s]).
- No string in the result contains the [sep] character.
@since 4.04.0
*)
(**/**)
(* The following is for system use only. Do not call directly. *)

View File

@ -21,3 +21,18 @@ let raw_string = build_string char 256 [];;
let ref_string = build_string reference 256 [];;
if String.escaped raw_string <> ref_string then failwith "test:String.escaped";;
let check_split sep s =
let l = String.split sep s in
assert(List.length l > 0);
assert(String.concat (String.make 1 sep) (String.split sep s) = s);
List.iter (String.iter (fun c -> assert (c <> sep))) l
;;
let () =
let s = " abc def " in
for i = 0 to String.length s do
check_split ' ' (String.sub s 0 i)
done
;;