Ocaml中的子字符串检查 [英] Substring check in Ocaml

查看:94
本文介绍了Ocaml中的子字符串检查的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以帮助我在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?

使用Str模块,我们可以这样做吗?

Using the Str module, can we do this?

推荐答案

类似的方法可能有效:

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

这篇关于Ocaml中的子字符串检查的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆