如何仅在 Ocaml 中的第一个空格上拆分字符串
How to split string only on first whitespace in Ocaml
我们如何在 Ocaml 中将字符串拆分为字符串列表,但仅限于第一个空格。
因此,例如:“你好我亲爱的朋友”变成了[“你好”; “我亲爱的朋友”]?
您可以使用标准 Str 库中的 bounded_split
:
(* Compile with: ocamlfind ocamlc -o example -package str -linkpkg example.ml *)
let split_on_first_space =
let re = Str.regexp "[ \t\r\n]" in
function s -> Str.bounded_split re s 2
let _ =
let str = "Hello my dear friend" in
match split_on_first_space str with
| [first; rest] ->
Printf.printf "%s and %s\n" first rest
| _ -> print_endline "No space in string!"
如果使用 Jane Street 的 Base 替换标准库,它的 String 模块有 lsplit2_exn
和 lsplit2
用于在给定字符第一次出现时将字符串分成两个:
(* Compile with ocamlfind ocamlc -o example -package base,stdio -linkpkg example.ml *)
open Base
let _ =
let str = "Hello my dear friend" in
begin
try
let (first, rest) = String.lsplit2_exn ~on:' ' str in
Stdio.printf "1: %s and %s\n" first rest;
with Not_found_s _ -> Stdio.print_endline "1: No space in string!"
end;
match String.lsplit2 ~on:' ' str with
| Some (first, rest) -> Stdio.printf "2: %s and %s\n" first rest
| None -> Stdio.print_endline "2: No space in string!"
当然,您可以使用默认标准库轻松实现 lsplit2
:
let lsplit2 str ~on =
let open String in
match index_opt str on with
| Some pos -> Some (sub str 0 pos,
sub str (pos + 1) (length str - pos - 1))
| None -> None
我们如何在 Ocaml 中将字符串拆分为字符串列表,但仅限于第一个空格。 因此,例如:“你好我亲爱的朋友”变成了[“你好”; “我亲爱的朋友”]?
您可以使用标准 Str 库中的 bounded_split
:
(* Compile with: ocamlfind ocamlc -o example -package str -linkpkg example.ml *)
let split_on_first_space =
let re = Str.regexp "[ \t\r\n]" in
function s -> Str.bounded_split re s 2
let _ =
let str = "Hello my dear friend" in
match split_on_first_space str with
| [first; rest] ->
Printf.printf "%s and %s\n" first rest
| _ -> print_endline "No space in string!"
如果使用 Jane Street 的 Base 替换标准库,它的 String 模块有 lsplit2_exn
和 lsplit2
用于在给定字符第一次出现时将字符串分成两个:
(* Compile with ocamlfind ocamlc -o example -package base,stdio -linkpkg example.ml *)
open Base
let _ =
let str = "Hello my dear friend" in
begin
try
let (first, rest) = String.lsplit2_exn ~on:' ' str in
Stdio.printf "1: %s and %s\n" first rest;
with Not_found_s _ -> Stdio.print_endline "1: No space in string!"
end;
match String.lsplit2 ~on:' ' str with
| Some (first, rest) -> Stdio.printf "2: %s and %s\n" first rest
| None -> Stdio.print_endline "2: No space in string!"
当然,您可以使用默认标准库轻松实现 lsplit2
:
let lsplit2 str ~on =
let open String in
match index_opt str on with
| Some pos -> Some (sub str 0 pos,
sub str (pos + 1) (length str - pos - 1))
| None -> None