Substring check in Ocaml

社会主义新天地 提交于 2019-12-30 08:03:15

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!