Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Substring check in Ocaml

Tags:

string

ocaml

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?

like image 820
priyanka Avatar asked Dec 04 '11 05:12

priyanka


People also ask

How do I compare strings in Ocaml?

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.

How do I combine two strings in Ocaml?

The (^) binary operator concatenates two strings.


1 Answers

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
like image 172
Jeffrey Scofield Avatar answered Oct 04 '22 22:10

Jeffrey Scofield