2012-06-25 132 views
0

有人可以幫我寫一個函數,檢查一個字符串是否是另一個字符串的子字符串?OCAML - 字符串和子字符串

(可以有比只有2字符串的更多)

由於

+2

什麼您的意思是「可以有超過只有2串」?至於字符串/子串測試,請參閱http://stackoverflow.com/q/8373460/520394。 –

+0

想向我們展示您的嘗試,以便我們能夠更高效地幫助您?幫助我們幫助你。 – Tim

回答

3

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 
+0

基於String的內存使用情況很可怕! –

+0

是的,但我認爲代碼會很容易理解爲新的OCaml用戶:-) – cago

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 
-6
String str="hello world"; 


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

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

問題是關於ocaml不是java – mou