2

Could someone help me to write a function that checks if a string is a substring of another string?

(there can be more than only 2 strings)

Thanks

2
  • 2
    What do you mean by 'there can be more than only 2 strings'? As for string/substring tests see stackoverflow.com/q/8373460/520394.
    – barti_ddu
    Jun 25, 2012 at 17:07
  • Want to show us your attempts so we can help you more efficiently? Help us help you.
    – Tim
    Jun 26, 2012 at 13:35

4 Answers 4

6

With String module:

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

With Str module, like @barti_ddu said check 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
2
  • The memory usage for the String-based one is scary ! Jun 26, 2012 at 12:28
  • Yes, but I thought that the code would be quite simple to understand for a new OCaml user :-) Jun 26, 2012 at 14:27
4

With Batteries, you can use String.exists. It also exists in ExtLib: String.exists.

2

A String-based alternative to cago's answer that might have better performance and lower memory usage:

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


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

System.out.println(str.contains("world1"));//false
1
  • 5
    the question was about ocaml not java Apr 21, 2017 at 8:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.