Learn/OCaml/8. Strings and a small project
Lesson 8 of 8
Sign in

OCaml, lesson 8

Strings and a small project

Text is everywhere: names, commands, lines of a file. OCaml strings are immutable sequences of bytes, and the String module has the tools to work with them.

The basics

s.[i] gives the character at position i, counting from 0. Characters are a different type from strings: 'H' is a char, "H" is a string. To turn a char into a one-letter string use String.make 1 c, and to change its case use Char.uppercase_ascii. %c prints a char in .

2 exercises to try what you just read.

Exercise 1

Initials

Press Ctrl Enter or Check to test your code.

Exercise 2

Receipt printer

Press Ctrl Enter or Check to test your code.

Printf

Because strings are immutable, functions like uppercase_ascii return a new string. The original is untouched.

Splitting and joining

String.split_on_char cuts a string at every occurrence of a character, and String.concat glues a list of strings together with a separator:

Filter out the empty pieces with List.filter (fun w -> w <> "") when the input may contain repeated spaces.

Checking and searching

~prefix: is a labelled argument: you name it when calling, which makes the call easier to read.

Building strings

For a few pieces, ^ or Printf.sprintf are best. sprintf works like printf but returns the string instead of printing it:

%-8s pads the string to 8 characters on the right, %5d pads the number to 5 on the left. This is handy for lining up columns.

Putting it together

The final exercise is a little receipt printer. It uses almost every lesson: reading input, converting text to numbers, a function, a fold over a list, string splitting and formatted output. Plan it before you type:

  1. Read all lines and drop empty ones.
  2. Split each line into a name, a quantity and a price.
  3. Print a line for each item, keeping running totals with List.fold_left.
  4. Print the totals.

Further reading

  • Module String
  • Module Printf
  • Labelled and Optional Arguments

Read a full name on one line. Print the initials in upper case, each followed by a dot. The name may be in any case and may contain extra spaces between words.

Sample input:

Sample output:

Each input line describes one item: a name, a quantity and a unit price, separated by single spaces. Prices are whole numbers. For every item print name: quantity x price = subtotal, then finish with the total number of items and the total cost. Ignore empty lines.

Sample input:

Sample output:

let s = "Hello, OCaml"

let () =
  Printf.printf "%d\n" (String.length s);        (* 12 *)
  Printf.printf "%c\n" s.[0];                    (* H  : a char *)
  print_endline (String.sub s 7 5);              (* OCaml : start 7, length 5 *)
  print_endline (String.uppercase_ascii s);      (* HELLO, OCAML *)
  print_endline (String.trim "  padded  ")       (* padded *)
let words = String.split_on_char ' ' "red green  blue"
(* ["red"; "green"; ""; "blue"] : two spaces in a row give an empty string *)

let csv = String.concat "," ["a"; "b"; "c"]    (* "a,b,c" *)
String.starts_with ~prefix:"http" url
String.ends_with ~suffix:".ml" file
String.contains "banana" 'n'           (* true *)
String.index_opt "banana" 'n'          (* Some 2 *)
let line = Printf.sprintf "%-8s %5d" "apples" 12   (* "apples      12" *)
grace brewster  hopper
G.B.H.
apple 3 2
bread 1 4
cheese 2 7
apple: 3 x 2 = 6
bread: 1 x 4 = 4
cheese: 2 x 7 = 14
Items: 6
Total: 24