OCaml Strings and Chars
An OCaml string is an immutable sequence of bytes. A char is a single byte. The String and Char modules contain the functions to work with them.
let () =
let s = "Functional" in
Printf.printf "length: %d\n" (String.length s);
Printf.printf "first: %c, last: %c\n" s.[0] s.[String.length s - 1];
Printf.printf "sub: %s\n" (String.sub s 0 3);
Printf.printf "upper: %s\n" (String.uppercase_ascii s);
Printf.printf "concat: %s\n" (s ^ " programming");
Printf.printf "equal: %b\n" (s = "Functional")length: 10
first: F, last: l
sub: Fun
upper: FUNCTIONAL
concat: Functional programming
equal: true
String.sub s start len extracts len characters starting at index start. Indexing out of range raises Invalid_argument.
Literals and escapes
| Escape | Meaning |
|---|---|
\n, \t, \r |
newline, tab, carriage return |
\\, \", \' |
backslash, double quote, single quote |
\065 |
byte by decimal code (A) |
\x41 |
byte by hex code (A) |
\u{1F42B} |
a Unicode code point, stored as UTF-8 |
Quoted strings {| ... |} contain text exactly as written, with no escapes. They are perfect for regular expressions, JSON or Windows paths:
let () =
print_endline "Tab:\tend, quote: \", backslash: \\";
print_endline {|C:\Users\ocaml\notes.txt|};
print_endline {|{"name": "camel", "humps": 2}|};
print_endline "\u{1F42B} OCaml"Tab: end, quote: ", backslash: \
C:\Users\ocaml\notes.txt
{"name": "camel", "humps": 2}
🐫 OCaml
Common String functions
let () =
let line = " apples, pears ,plums " in
let parts = String.split_on_char ',' line |> List.map String.trim in
print_endline (String.concat "|" parts);
Printf.printf "%b %b\n" (String.starts_with ~prefix:"ap" "apples") (String.ends_with ~suffix:"ms" "plums");
Printf.printf "%b\n" (String.contains "pears" 'r');
Printf.printf "%d\n" (String.index "banana" 'n');
Printf.printf "%d\n" (String.rindex "banana" 'n');
print_endline (String.capitalize_ascii "ocaml");
print_endline (String.make 5 '=');
print_endline (String.concat ", " [ "one"; "two"; "three" ])apples|pears|plums
true true
true
2
4
Ocaml
=====
one, two, three
There is no built-in "find a substring" function in String. You can write one with String.sub, or use the Str library or the re package in a real project.
Working character by character
String.iter, String.map, String.fold_left and friends process each character. Char provides tests and conversions:
let count_vowels s =
String.fold_left (fun n c -> if String.contains "aeiou" (Char.lowercase_ascii c) then n + 1 else n) 0 s
let caesar shift s =
String.map
(fun c ->
if c >= 'a' && c <= 'z' then Char.chr (((Char.code c - 97 + shift) mod 26) + 97)
else c)
s
let () =
Printf.printf "%d\n" (count_vowels "Programming In OCaml");
print_endline (caesar 3 "hello world");
print_endline (caesar 23 (caesar 3 "hello world"));
String.iteri (fun i c -> if i < 3 then Printf.printf "%d:%c " i c) "camel";
print_newline ()6
khoor zruog
hello world
0:c 1:a 2:m
Converting to and from lists and sequences
let is_palindrome s =
let letters = s |> String.lowercase_ascii |> String.to_seq |> Seq.filter (fun c -> c <> ' ') |> String.of_seq in
let reversed = String.init (String.length letters) (fun i -> letters.[String.length letters - 1 - i]) in
letters = reversed
let () =
List.iter (fun s -> Printf.printf "%-28s %b\n" s (is_palindrome s))
[ "racecar"; "Never odd or even"; "OCaml" ]racecar true
Never odd or even true
OCaml false
String.init n f builds a string of length n whose character i is f i.
Strings are bytes, not characters
String.length counts bytes. A non-ASCII character in UTF-8 takes 2 to 4 bytes:
let () =
let word = "café" in
Printf.printf "bytes: %d\n" (String.length word);
let decoder = String.get_utf_8_uchar word 3 in
Printf.printf "char at byte 3 uses %d bytes, code point U+%04X\n"
(Uchar.utf_decode_length decoder) (Uchar.to_int (Uchar.utf_decode_uchar decoder))bytes: 5
char at byte 3 uses 2 bytes, code point U+00E9
For serious Unicode text (counting user-visible characters, case folding), use a library such as uutf/uucp.
Note: Strings cannot be modified.
s.[0] <- 'x'does not compile. For text you build piece by piece, useBuffer(next lesson); for mutable byte arrays, useBytes.
Test yourself
What does String.sub "lambda" 1 3 return?
"lam""amb""ambd""mbd"
What is String.length "é" in OCaml?
- 1
- 2
- 0
- It does not compile
Which literal contains a backslash without any escaping?
"a\b"{|a\b|}'a\b'r"a\b"