Commits

Anonymous committed 9628fc4

String: + find_substring

  • Participants
  • Parent commits c17ac92

Comments (0)

Files changed (1)

File src/cd_Strings.ml

         value compare_nocase_latin1 : string -> string -> int;
         (* } from amall *)
 
+        (* [find_substring str sub] returns -1 if [sub] is not found in [str];
+           first offset otherwise.
+         *)
+        value find_substring : string -> string -> int;
+
         value of_bytes : Cd_Bytes.Bytes.t -> string;
         value of_char : char -> string;
         value length_bytes : string -> int;
 
         value hexdump = Cd_Bytes.Bytes.hexdump;
 
+        value find_substring str sub =
+          let str_len = String.length str
+          and sub_len = String.length sub in
+          let iend = str_len - sub_len + 1 in 
+          if iend <= 0
+          then -1
+          else
+            loop 0
+            where rec loop i =
+              if i = iend
+              then -1
+              else
+                let rec is_here j =
+                  if j = sub_len
+                  then True
+                  else
+                    if str.[i + j] = sub.[j]
+                    then is_here (j + 1)
+                    else False
+                in
+                  if is_here 0
+                  then i
+                  else loop (i + 1)
+        ;
+
         include TCommon;
 
       end