Does OCaml have String.split function like Python?

后端 未结 4 599
离开以前
离开以前 2021-01-12 01:24

I am using this to split strings:

 let split = Str.split (Str.regexp_string \" \") in
   let tokens = split instr in
 ....

But the problem

相关标签:
4条回答
  • 2021-01-12 01:38

    Using Jane Street's Core library, you can do:

    let python_split x =
      String.split_on_chars ~on:[ ' ' ; '\t' ; '\n' ; '\r' ] x
      |> List.filter ~f:(fun x -> x <> "")
    ;;
    
    0 讨论(0)
  • 2021-01-12 01:39

    Since OCaml 4.04.0 there is also String.split_on_char, which you can combine with List.filter to remove empty strings:

    # "pop     esi"
      |> String.split_on_char ' '
      |> List.filter (fun s -> s <> "");;
    - : string list = ["pop"; "esi"]
    

    No external libraries required.

    0 讨论(0)
  • 2021-01-12 01:52

    This is how I split my lines into words:

    open Core.Std
    let tokenize line = String.split line ~on: ' ' |> List.dedup
    

    Mind the single quotes around the space character.

    Here's the documentation for String.split: link

    0 讨论(0)
  • 2021-01-12 01:59

    Don't use Str.regexp_string, it's only for matching fixed strings.

    Use Str.split (Str.regexp " +")

    0 讨论(0)
提交回复
热议问题