Skip to content

Commit

Permalink
added count_string
Browse files Browse the repository at this point in the history
  • Loading branch information
Francois BERENGER committed Oct 23, 2017
1 parent e069e28 commit 1171462
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 1 deletion.
4 changes: 4 additions & 0 deletions src/batString.mliv
Original file line number Diff line number Diff line change
Expand Up @@ -540,6 +540,10 @@ val find_all : string -> string -> int BatEnum.t
the list [[1; 4]].
@since 2.2.0 *)

val count_string : string -> string -> int
(** [count_string s x] count how many times [x] is found in [s].
@since NEXT_RELEASE *)

val ends_with : string -> string -> bool
(** [ends_with s x] returns [true] if the string [s] is ending with [x], [false] otherwise.

Expand Down
23 changes: 22 additions & 1 deletion src/batString.mlv
Original file line number Diff line number Diff line change
Expand Up @@ -205,7 +205,28 @@ let find_all str sub =
let e = find_all "aaabbaabaaa" "aa" in \
Enum.drop 2 e; let e' = Enum.clone e in \
(List.of_enum e = [5;8;9]) && (Enum.skip 1 e' |> List.of_enum = [8;9])
*)
*)

let count_string str sub =
if sub = "" then raise (Invalid_argument "String.count_string");
let m = length str in
let n = length sub in
let rec loop acc i =
if i >= m then
acc
else
try
let j = find_from str i sub in
loop (acc + 1) (j + n)
with Not_found -> acc
in
loop 0 0
(*$T count_string
try let _ = count_string "abc" "" in false with Invalid_argument _ -> true
count_string "aaa" "a" = 3
count_string "aaa" "aa" = 1
count_string "coucou" "cou" = 2
*)

let exists str sub =
try
Expand Down

0 comments on commit 1171462

Please sign in to comment.