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?
You can compare strings with the usal comparison operators: = , <> , < , <= , > , >= . You can also use the compare function, which returns -1 if the first string is less than the second, 1 if the first string is greater than the second, and 0 if they are equal.
The (^) binary operator concatenates two strings.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With