要学习OCaml的基础知识,我正在使用它来解决一个简单的facebook工程难题.基本上,我想做类似以下Python代码的事情:
some_str = some_str.strip()
Run Code Online (Sandbox Code Playgroud)
也就是说,我想从开头和结尾去掉所有的空白.我没有在OCaml Str库中看到任何明显的事情.有没有简单的方法来做到这一点,或者我将不得不写一些代码来做它(我不介意,但不想:)).
请记住,我仅限于OCaml发行版附带的库中的内容.
我知道这个问题已经过时了,但我只是在思考同样的事情并且想出了这个问题(来自顶层):
let strip str =
let str = Str.replace_first (Str.regexp "^ +") "" str in
Str.replace_first (Str.regexp " +$") "" str;;
val strip : string -> string = <fun>
Run Code Online (Sandbox Code Playgroud)
然后
strip " Hello, world! ";;
- : string = "Hello, world!"
Run Code Online (Sandbox Code Playgroud)
更新:
从4.00.0开始,标准库包含String.trim
将自己限制在标准库中真的是一个错误,因为标准的图书馆缺少很多东西.例如,如果你使用Core,你可以简单地做:
open Core.Std
let x = String.strip " foobar "
let () = assert (x = "foobar")
Run Code Online (Sandbox Code Playgroud)
如果您想查看实现,您当然可以查看Core的来源.ExtLib中有类似的功能.
怎么样
let trim str =
if str = "" then "" else
let search_pos init p next =
let rec search i =
if p i 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" -> ""
Run Code Online (Sandbox Code Playgroud)
(通过Code Codex)