How to remove spaces from a string in OCaml?

To learn the basics of OCaml, I solve one of the simple puzzle-programmers . Essentially, I would like to do something like the following Python code:

some_str = some_str.strip() 

That is, I would like to remove all the gaps from beginning to end. I do not see anything obvious for this in the OCaml Str library. Is there any simple way to do this, or will I have to write some code for this (which I would not mind, but would prefer not :) :).

Keep in mind that I am limited to the libraries that come with the OCaml distribution.

+6
string ocaml
source share
5 answers

What about

 let trim str = if str = "" then "" else let search_pos init p next = let rec search i = if pi then raise(Failure "empty") else match str.[i] with | ' ' | '\n' | '\r' | '\t' -> search (next i) | _ -> i in search init in let len = String.length str in try let left = search_pos 0 (fun i -> i >= len) (succ) and right = search_pos (len - 1) (fun i -> i < 0) (pred) in String.sub str left (right - left + 1) with | Failure "empty" -> "" 

(Via Code Codex )

+5
source share

I know this question is uber-old, but I just thought 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:

Starting at 4.00.0, the standard library includes String.trim

+8
source share

It’s really a mistake to limit yourself to a standard library, since there are a lot of things missing from the standard Ibrashnik. If, for example, you were to use Core, you could just do:

 open Core.Std let x = String.strip " foobar " let () = assert (x = "foobar") 

You can, of course, look at the Core sources if you want to see the implementation. A similar function exists in ExtLib.

+5
source share

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 "" ;; 
+1
source share

Something simple how this should work fine:

  #require "str";; let strip_string s = Str.global_replace (Str.regexp "[\r\n\t ]") "" s 
0
source share

All Articles