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:   TEST

This example demonstrates various string operations in OCaml. Note that OCaml’s standard library functions often differ slightly from those in other languages:

  1. String.contains checks for the presence of a character, not a substring.
  2. There’s no direct count function, so we use String.fold_left to count occurrences.
  3. String.starts_with and String.ends_with are used for prefix and suffix checks.
  4. String.index finds the position of a character.
  5. String.concat joins strings with a delimiter.
  6. String.make repeats a character.
  7. String.map and String.mapi are used for character replacement.
  8. String.split_on_char splits a string on a delimiter.
  9. 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.