The standard library’s String module provides many useful string-related functions. Here are some examples to give you a sense of the module.
To run the program, save it as string_functions.ml and use ocaml to execute it:
This example demonstrates various string operations in OCaml. Note that OCaml’s standard library functions often differ slightly from those in other languages:
String.contains checks for the presence of a character, not a substring.
There’s no direct count function, so we use String.fold_left to count occurrences.
String.starts_with and String.ends_with are used for prefix and suffix checks.
String.index finds the position of a character.
String.concat joins strings with a delimiter.
String.make repeats a character.
String.map and String.mapi are used for character replacement.
String.split_on_char splits a string on a delimiter.
String.lowercase_ascii and String.uppercase_ascii change 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.