Reputation: 135
So I'm writing a JSON parser in OCaml, and I need to get a slice of a string. More specifically, I need to get the first n characters of a string so I can pattern-match with them.
Here's an example string:
"null, \"field2\": 25}"
So, how could I use just a couple lines of OCaml code to get just the first 4 characters (the null
)?
P.S. I've already thought about using something like input.[0..4]
but I'm not entirely sure how that works, I'm reasonably new to OCaml and the ML family.
Upvotes: 2
Views: 2411
Reputation: 803
Using build-in sub
function should do the work:
let example_string = "null, \"field2\": 25}"
(*val example_string : string = "null, \"field2\": 25}" *)
let first_4 = String.sub example_string 0 4
(*val first_4 : string = "null" *)
I suggest you to look at official documentation: https://caml.inria.fr/pub/docs/manual-ocaml/libref/String.html
And if you are not doing this for self teaching I would strongly suggest using one of available libraries for the purpose, such as yojson (https://ocaml-community.github.io/yojson/yojson/Yojson/index.html) for example.
Upvotes: 4