String Functions in OCaml
The standard library’s String module provides many useful string-related functions. Here are some examples to give you a sense of the module.
open Printf
(* We use printf instead of a custom print function *)
let main () =
(* Here's a sample of the functions available in String.
You can find more functions in the String module documentation. *)
printf "Contains: %b\n" (String.contains "test" 'e');
printf "Count: %d\n" (String.fold_left (fun acc c -> if c = 't' then acc + 1 else acc) 0 "test");
printf "HasPrefix: %b\n" (String.starts_with ~prefix:"te" "test");
printf "HasSuffix: %b\n" (String.ends_with ~suffix:"st" "test");
printf "Index: %d\n" (String.index "test" 'e');
printf "Join: %s\n" (String.concat "-" ["a"; "b"]);
printf "Repeat: %s\n" (String.make 5 'a');
printf "Replace: %s\n" (String.map (fun c -> if c = 'o' then '0' else c) "foo");
printf "Replace: %s\n" (String.mapi (fun i c -> if i = 1 && c = 'o' then '0' else c) "foo");
printf "Split: %s\n" (String.split_on_char '-' "a-b-c-d-e" |> String.concat " ");
printf "ToLower: %s\n" (String.lowercase_ascii "TEST");
printf "ToUpper: %s\n" (String.uppercase_ascii "test")
let () = main ()To run the program, save it as string_functions.ml and use ocaml to execute it:
$ ocaml string_functions.ml
Contains: true
Count: 2
HasPrefix: true
HasSuffix: true
Index: 1
Join: a-b
Repeat: aaaaa
Replace: f00
Replace: f0o
Split: a b c d e
ToLower: test
ToUpper: TESTThis example demonstrates various string operations in OCaml. Note that OCaml’s standard library functions often differ slightly from those in other languages:
String.containschecks for the presence of a character, not a substring.- There’s no direct
countfunction, so we useString.fold_leftto count occurrences. String.starts_withandString.ends_withare used for prefix and suffix checks.String.indexfinds the position of a character.String.concatjoins strings with a delimiter.String.makerepeats a character.String.mapandString.mapiare used for character replacement.String.split_on_charsplits a string on a delimiter.String.lowercase_asciiandString.uppercase_asciichange the case of ASCII characters.
OCaml’s string functions are generally more functional in nature, often using higher-order functions like map and fold where other languages might use imperative loops.
Comments powered by Disqus