OCAML - strings and substrings

12,182

Solution 1

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

Solution 2

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

Solution 3

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
Share:
12,182
prmz
Author by

prmz

Updated on June 04, 2022

Comments

  • prmz
    prmz almost 2 years

    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