OCAML - 字符串和子串

时间:2012-06-25 16:59:15

标签: string ocaml substring

有人可以帮我编写一个函数来检查字符串是否是另一个字符串的子字符串吗?

(可能只有2个字符串)

由于

4 个答案:

答案 0 :(得分:4)

使用String模块:

let contains s1 s2 =
  try
    let len = String.length s2 in
    for i = 0 to String.length s1 - len do
      if String.sub s1 i len = s2 then raise Exit
    done;
    false
  with Exit -> true

使用Str模块,比如@barti_ddu说检查this topic

let contains s1 s2 =
    let re = Str.regexp_string s2 in
    try 
       ignore (Str.search_forward re s1 0); 
       true
    with Not_found -> false

答案 1 :(得分:4)

使用电池,您可以使用String.exists。它也存在于ExtLib中:String.exists

答案 2 :(得分:1)

基于String的替代cago的答案,可能有更好的性能和更低的内存使用率:

let is_substring string substring = 
  let ssl = String.length substring and sl = String.length string in 
  if ssl = 0 || ssl > sl then false else 
    let max = sl - ssl and clone = String.create ssl in
    let rec check pos = 
      pos <= max && (
        String.blit string pos clone 0 ssl ; clone = substring 
        || check (String.index_from string (succ pos) substring.[0])
      )
    in             
    try check (String.index string substring.[0])
    with Not_found -> false

答案 3 :(得分:-9)

String str="hello world";


System.out.println(str.contains("world"));//true

System.out.println(str.contains("world1"));//false