Strings, Chars, Bytes, Buffer & Printf
15.1 String module
Strings are immutable byte sequences. They can hold UTF-8 but length counts bytes; use String.get_utf_8_uchar / Uchar or libraries like uutf/uucp for Unicode.
String.length "hello" (* 5 *)
String.get "hello" 0 (* 'h'; same as "hello".[0] *)
String.sub "hello world" 6 5 (* "world" *)
String.concat ", " ["a";"b";"c"] (* "a, b, c" *)
String.split_on_char ' ' "a b c" (* ["a";"b";"c"] *)
String.trim " hi " (* "hi" *)
String.uppercase_ascii, String.lowercase_ascii, String.capitalize_ascii
String.contains "hello" 'e' (* true *)
String.index "hello" 'l' (* 2, raises Not_found *)
String.index_opt
String.starts_with ~prefix:"he" "hello" (* true *)
String.ends_with ~suffix:"lo" "hello"
String.make 3 'x' (* "xxx" *)
String.init 3 (fun i -> Char.chr (97 + i)) (* "abc" *)
String.map Char.uppercase_ascii "abc"
String.iter print_char "abc"
String.fold_left (fun acc c -> acc + Char.code c) 0 "ab"
String.equal, String.compare
String.to_seq, String.of_seq
String.exists, String.for_all
String.cat "a" "b"15.2 Raw / quoted strings
let regex = {|\d+\.\d+|} (* no escape processing *)
let html = {html|<p class="x">|}|html}15.3 Char
Char.code 'a', Char.chr 98, Char.uppercase_ascii 'a', Char.escaped '\n'
match c with 'a' .. 'z' -> `Lower | 'A' .. 'Z' -> `Upper | '0' .. '9' -> `Digit | _ -> `Other15.4 Bytes — mutable byte sequences
let b = Bytes.of_string "hello"
let () = Bytes.set b 0 'J'
let s = Bytes.to_string b (* "Jello" *)
Bytes.create 10, Bytes.make 3 'a', Bytes.blit, Bytes.sub_string15.5 Buffer — efficient string building
Avoid repeated ^ in loops (quadratic).
let csv_line fields =
let buf = Buffer.create 64 in
List.iteri (fun i f ->
if i > 0 then Buffer.add_char buf ',';
Buffer.add_string buf f) fields;
Buffer.contents buf15.6 Printf
int unsigned/hex/octal string (S = OCaml-escaped) custom printer (out -> 'a -> unit) -> 'a (out -> unit)
Format strings are type-checked at compile time — Printf.printf "%d" "x" is a type error.
Printf.printf "Name: %s, Age: %d, Score: %.2f\n" "Ann" 30 95.456
let s = Printf.sprintf "%05d|%-8s|%x|%c|%b" 42 "left" 255 'z' true
Printf.eprintf "error: %s\n" "boom" (* to stderr *)
Printf.fprintf oc "%s\n" line (* to channel *)
Printf.printf "%a\n" (fun oc p -> Printf.fprintf oc "(%d,%d)" (fst p) (snd p)) (1,2)15.7 Scanf
let () = Scanf.scanf " %d %d" (fun a b -> Printf.printf "%d\n" (a + b))
let (x, y) = Scanf.sscanf "3,4" "%d,%d" (fun a b -> (a, b))15.8 Regular expressions
Str (bundled): #require "str", Str.regexp, Str.split, Str.global_replace.
re (recommended, opam): Re.Pcre.regexp, Re.execp, Re.all.
let re = Re.Pcre.regexp {|(\d+)-(\d+)|}
let groups = Re.exec re "10-20"
let a = Re.Group.get groups 1 (* "10" *)