I have a string (on a single line) and the idea is to iterate the string from a given position in the string, go left character by character and stop when we meet a separator (the separators are in the list), and do the same on the right and at the end, put the two together to form the word you are looking for. I wrote the following function, but it doesn't quite work, when I position myself at the end of a word like in position 4, it returns me a string "" instead of returning "this". When I go to position 1, it sends me "his" and not "this". When I put myself in position 44, I output "tha" instead of "that". On the other hand, in the middle of the string as for position 36 or 40, it works.
(* separators *)let sep_list = [';';',';'(';')';'.';'';](* my string to test *)let my_str = "this is my string for testing purpose, only that"(* my function *)let search_word_in_cursor (str:string) (char_list:char list) (pos:int) : string = let rec foo_left (str:string) (char_list:char list) (pos:int) (ret:string) : string = if ((List.exists (fun x -> Char.equal x str.[pos]) char_list) || (pos <= 0)) then ret else if (pos == 0) then String.make 1 str.[pos] ^ ret else foo_left str char_list (pos - 1) ((String.make 1 str.[pos]) ^ ret) in let rec foo_right (str:string) (char_list:char list) (pos:int) (ret:string) : string = if ((List.exists (fun x -> Char.equal x str.[pos]) char_list) || (pos >= (String.length str - 1))) then ret else foo_right str char_list (pos + 1) (ret ^ (String.make 1 str.[pos])) in let sl = foo_left str char_list pos "" in let sr = foo_right str char_list pos "" in if (sr == "" && sl == "") then "" else if (sr == "" && sl != "") then sl else if (sr != "" && sl == "") then sr else (String.sub sl 0 (String.length sl - 1)) ^ sr(* expects and results *)let () = print_string (search_word_in_cursor my_str sep_list 4); (* expected:"this" output:"" *) print_string (search_word_in_cursor my_str sep_list 1); (* expected:"this" output:"his" *) print_string (search_word_in_cursor my_str sep_list 44); (* expected:"that" output:"tha" *) print_string (search_word_in_cursor my_str sep_list 36); (* expected:"purpose" output:"purpose" *) print_string (search_word_in_cursor my_str sep_list 40) (* expected:"only" output:"only" *)