I believe that at the moment when other answers were given, version 4.00 has not yet been released. In fact, in OCaml 4.00, the string module has a String.trim function to trim the spaces in the top and back spaces.
Alternatively, if you are limited to an older version of OCaml, you can use this function, which is shamelessly copied from the source of 4.00 string module.
let trim s = let is_space = function | ' ' | '\012' | '\n' | '\r' | '\t' -> true | _ -> false in let len = String.length s in let i = ref 0 in while !i < len && is_space (String.get s !i) do incr i done; let j = ref (len - 1) in while !j >= !i && is_space (String.get s !j) do decr j done; if !i = 0 && !j = len - 1 then s else if !j >= !i then String.sub s !i (!j - !i + 1) else "" ;;
Jason yeo
source share