Added two new optional arguments to nsplit: * noempty: if set to false empty elements are not stored in the returned list. The default is to keep the empty elements * count: specifies how many splits to perform; negative count (the default) means do as many splits as possible Signed-off-by: Tomáš Golembiovský <tgolembi@redhat.com> --- mllib/common_utils.ml | 12 +++++++++--- mllib/common_utils.mli | 12 ++++++++++-- 2 files changed, 19 insertions(+), 5 deletions(-) diff --git a/mllib/common_utils.ml b/mllib/common_utils.ml index 78618f5..2d373f9 100644 --- a/mllib/common_utils.ml +++ b/mllib/common_utils.ml @@ -92,15 +92,21 @@ module String = struct s' ^ s2 ^ replace s'' s1 s2 ) - let rec nsplit sep str = + let rec nsplit ?(noempty = true) ?(count = -1) sep str = let len = length str in let seplen = length sep in let i = find str sep in - if i = -1 then [str] + if i = -1 || count = 0 then [str] else ( let s' = sub str 0 i in let s'' = sub str (i+seplen) (len-i-seplen) in - s' :: nsplit sep s'' + let elem, count = + if s' = "" && noempty then + [], count + else + [s'], if count > 0 then count-1 else count + in + elem @ nsplit ~noempty:noempty ~count:count sep s'' ) let split sep str = diff --git a/mllib/common_utils.mli b/mllib/common_utils.mli index ad43345..bcd459d 100644 --- a/mllib/common_utils.mli +++ b/mllib/common_utils.mli @@ -64,9 +64,17 @@ module String : sig val replace : string -> string -> string -> string (** [replace str s1 s2] replaces all instances of [s1] appearing in [str] with [s2]. *) - val nsplit : string -> string -> string list + val nsplit : ?noempty:bool -> ?count:int -> string -> string -> string list (** [nsplit sep str] splits [str] into multiple strings at each - separator [sep]. *) + separator [sep]. + + If [noempty] is set to true empty elements are not included in the + list. By default empty elements are kept. + + If [count] is specified it says how many splits to perform. I.e. the + returned array will have at most [count]+1 elements. Negative [count] + (the default) means do as many splits as possible. + *) val split : string -> string -> string * string (** [split sep str] splits [str] at the first occurrence of the separator [sep], returning the part before and the part after. -- 2.10.2