有人可以帮我写一个函数来检查一个字符串是否是另一个字符串的子字符串吗?
(可以有不止 2 个字符串)
谢谢
带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
使用电池,您可以使用String.exists。它也存在于 ExtLib: String.exists中。
基于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
String str="hello world";
System.out.println(str.contains("world"));//true
System.out.println(str.contains("world1"));//false