Version française
Home     About     Download     Resources     Contact us    
Browse thread
index of substring
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: -- (:)
From: yjc01@d...
Subject: index of substring
I tried to write a function to return the index of a substring in a string from
an index. So I can use it to extract some comments (text between (* and *) in a
file. But came across some problem when returning the value.

The code I came up with is: 
(* Use Unix Module *)
open Unix;;


(* get the file size *)
let fileReader = openfile "student.cd" [O_RDONLY] 0o640;;
let fileSize = (fstat fileReader).st_size;;
print_int fileSize;;

(* create variable to store file *)
let comments = String.make fileSize 'c';;

 
let read_char () = 
	read fileReader comments 0 fileSize;;


(* return index of a substring in a string from an index, if substring not
matched retun -1 *)
let index_left fromIndex string findString = 
	(* Step 1. Find first character *)
	let firstIndex = String.index_from string fromIndex (String.get findString 0) in
	
	   if (firstIndex >= 0)	then
		let isMatched = ref true in
		for i = 1 to (String.length findString) do
			if (String.get string firstIndex) != (String.get findString 0) 
			   then !isMatched = false;
			if (!isMatched)
			   then firstIndex 
			   else -1;
			
		done;;
				
(* test if index_left works *)
let check index = 
	 index_left index comments "(*" 
		

print_int check 1;;


Or is there an easier way to do this?

Daisy