2

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

(可以有不止 2 个字符串)

谢谢

4

4 回答 4

6

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 说的检查这个主题

let contains s1 s2 =
    let re = Str.regexp_string s2 in
    try 
       ignore (Str.search_forward re s1 0); 
       true
    with Not_found -> false
于 2012-06-26T08:15:05.137 回答
4

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

于 2012-06-26T11:21:23.973 回答
2

基于cagoString的答案的替代方案,可能具有更好的性能和更低的内存使用量:

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
于 2012-06-26T12:56:34.073 回答
-10
String str="hello world";


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

System.out.println(str.contains("world1"));//false
于 2013-04-24T17:45:21.180 回答