Reputation: 943
Can someone help me in coding an effective substring check in OCaml? Given two strings, check whether the first one contains the second one?
Using the Str
module, can we do this?
Upvotes: 21
Views: 10015
Reputation: 2368
let contains_substring search target =
String.substr_index search target <> None
Upvotes: -1
Reputation: 66803
Something like this might work:
let contains s1 s2 =
let re = Str.regexp_string s2
in
try ignore (Str.search_forward re s1 0); true
with Not_found -> false
Here are some tests of the function:
# contains "abcde" "bc";;
- : bool = true
# contains "abcde" "bd";;
- : bool = false
# contains "abcde" "b.";;
- : bool = false
# contains "ab.de" "b.";;
- : bool = true
Upvotes: 17