Home > Software design >  How to delete all char of a string in OCaml
How to delete all char of a string in OCaml

Time:11-26

Is there an easy way to delete all occurrences of a char in an OCaml string ?

I thought I could use this clean function :

let clean = 
  function 
  | ' ' | '[' | ']' | '\n' | '>' -> '' 
  | x -> x 
in 

But you can't use '' in OCaml.

So I came with this solution :

let delete = 
  function 
    | ' ' | '[' | ']' | '\n' | '>' -> true 
    | _ -> false 
  in 
  let char_list, size =
    String.fold_left 
      (fun (acc, count) c -> 
        if delete c then acc, count 
        else c::acc, count 1) ([],0) path_string 
  in
  let char_list = ref @@ List.rev char_list in 
  let aux() = 
    match !char_list with 
    | [] -> failwith "unexpected"
    | x :: xs -> char_list := xs; x
  in
  let cleaned_string = String.init size (fun _ -> aux()) in 
  cleaned_string

But it's big - with python it's just s.replace('>','') to suppress one - and only work with OCaml 4.13 which is not supported for my installation.

CodePudding user response:

If you want to build a string dynamically, you should use a buffer

let remove_chars erase s =
  let b = Buffer.create 10 in
  String.iter (fun c -> if not (erase c) then Buffer.add_char b c);
  Buffer.contents b

(Building a list of characters is extremely inefficient.)

CodePudding user response:

The closest equivalent to python might be Str.global_replace:

Str.(global_replace (regexp ">") "" s)

or to do multiple characters at once you could do something like:

Str.(global_replace (regexp {|[][> \n]|}) "" s)
  • Related