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

Pascal Cuoq
  • 79,187
  • 7
  • 161
  • 281
prmz
  • 311
  • 1
  • 3
  • 13
  • 2
    What do you mean by 'there can be more than only 2 strings'? As for string/substring tests see http://stackoverflow.com/q/8373460/520394. – barti_ddu Jun 25 '12 at 17:07
  • Want to show us your attempts so we can help you more efficiently? Help us help you. – Tim Jun 26 '12 at 13:35

4 Answers4

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
Community
  • 1
  • 1
Çağdaş Bozman
  • 2,537
  • 16
  • 21
4

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

Quentin Pradet
  • 4,691
  • 2
  • 29
  • 41
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
Victor Nicollet
  • 24,361
  • 4
  • 58
  • 89
-17
String str="hello world";


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

System.out.println(str.contains("world1"));//false
unkulunkulu
  • 11,576
  • 2
  • 31
  • 49
zaki
  • 1