File: strpos.ml

package info (click to toggle)
ocaml-doc 3.09-1
  • links: PTS
  • area: non-free
  • in suites: etch, etch-m68k
  • size: 10,428 kB
  • ctags: 4,963
  • sloc: ml: 9,244; makefile: 2,413; ansic: 122; sh: 49; asm: 17
file content (60 lines) | stat: -rw-r--r-- 2,100 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
(***********************************************************************)
(*                                                                     *)
(*                           Objective Caml                            *)
(*                                                                     *)
(*               Pierre Weis, projet Cristal, INRIA Rocquencourt       *)
(*                                                                     *)
(*  Copyright 2001 Institut National de Recherche en Informatique et   *)
(*  en Automatique.  All rights reserved.  This file is distributed    *)
(*  only by permission.                                                *)
(*                                                                     *)
(***********************************************************************)

(* Find the first occurrence of string [p] (the so-called ``pattern'')
   into the string [s].
   Naive algorithm. *)

let find_sub_string p s =
  let plen = String.length p in
  if plen = 0 then 0 else
  let slen = String.length s in
  if slen = 0 then raise Not_found else
  let rec find c i =
    if i >= slen then raise Not_found else
    if s.[i] = c then find_rest c 1 (i + 1) else find c (i + 1)
   and find_rest c j i =
    if j >= plen then (i - plen) else
    if i >= slen then raise Not_found else
    if p.[j] = s.[i] then find_rest c (j + 1) (i + 1) else
    find c (i + 1 - j) in
  find p.[0] 0;;

let find_pat p s =
  try
    let i = find_sub_string p s in
    print_string "Match found at character ";
    print_int i;
    print_newline ();
    exit 0
  with Not_found ->
    print_string "Pattern ";
    print_string p;
    print_string " does not match string ";
    print_string s;
    print_newline ();
    exit 2;;

let usage () =
  print_string
   "Usage: strstr2 <pat> <str>\n\
    returns the index of the first occurrence of <pat> in string <str>\n";
  exit 2;;

let main () =
  let args = Sys.argv in
  if Array.length args < 2 then usage () else
   let p = Sys.argv.(1)
   and s = Sys.argv.(2) in
  find_pat p s;;

if !Sys.interactive then () else main ();;