Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I strip whitespace from a string in OCaml?

Tags:

string

ocaml

To learn the basics of OCaml, I'm solving one of the easy facebook engineering puzzles using it. Essentially, I'd like to do something like the following Python code:

some_str = some_str.strip()

That is, I'd like to strip all of the whitespace from the beginning and the end. I don't see anything obvious to do this in the OCaml Str library. Is there any easy way to do this, or am I going to have to write some code to do it (which I wouldn't mind, but would prefer not to :) ).

Bear in mind that I'm limited to what's in the libraries that come with the OCaml distribution.

like image 550
Jason Baker Avatar asked Oct 18 '09 12:10

Jason Baker


2 Answers

I know this question is uber-old, but I was just pondering the same thing and came-up with this (from toplevel):

let strip str = 
  let str = Str.replace_first (Str.regexp "^ +") "" str in
  Str.replace_first (Str.regexp " +$") "" str;;           
val strip : string -> string = <fun>

then

strip "   Hello, world!   ";;
- : string = "Hello, world!"

UPDATE:

As of 4.00.0, standard library includes String.trim

like image 114
lebowski Avatar answered Sep 21 '22 21:09

lebowski


It is really a mistake to limit yourself to the standard library, since the standard ilbrary is missing a lot of things. If, for example, you were to use Core, you could simply do:

open Core.Std

let x = String.strip "  foobar   "
let () = assert (x = "foobar")

You can of course look at the sources of Core if you want to see the implementation. There is a similar function in ExtLib.

like image 42
zrr Avatar answered Sep 22 '22 21:09

zrr