问题
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?
回答1:
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
回答2:
let contains_substring search target =
String.substr_index search target <> None
来源:https://stackoverflow.com/questions/8373460/substring-check-in-ocaml