Does OCaml have String.split function like Python?

最后都变了- 提交于 2019-12-30 08:51:49

问题


I am using this to split strings:

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

But the problem is that for example here is a sentence I want to parse:

pop     esi

and after the split it turns to be (I use a helper function to print each item in the tokens list):

item: popitem: item: item: item: esi

See, there are three spaces in the token list.

I am wondering if there is a string.split like in Python which can parse instr this way:

item: popitem: esi

Is it possible?


回答1:


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

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




回答2:


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 <> "")
;;



回答3:


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




回答4:


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.



来源:https://stackoverflow.com/questions/23204953/does-ocaml-have-string-split-function-like-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!