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

F#, lesson 8

Strings and a small project

Text is everywhere: names, commands, lines of input. F# strings are .NET strings, so you get both F#'s own String module and all the .NET string methods.

The basics

Positions count from 0. s[i] gives a char, which is a different type from a one-letter string: 'H' versus "H". Turn a char into a string with string c, and change its case with Char.ToUpper c (after open System).

Strings are immutable: ToUpper() returns a new string and leaves the original alone.

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.

Splitting and joining

Split cuts a string into an array of pieces. StringSplitOptions.RemoveEmptyEntries drops the empty pieces you get from repeated separators:

Checking and searching

Building strings

Interpolated strings are the most readable way to build text. Add a format specifier before the braces when you want the type checked or the number formatted:

sprintf works like printfn but returns the string instead of printing it. %-8s pads to 8 characters on the right; %5d pads to 5 on the left. That is handy for lining up columns.

Putting it together

The last exercise is a small receipt printer that uses nearly every lesson: reading input, converting text to numbers, a function, pattern matching, a fold over a list, and formatted output. Plan first:

  1. Read all lines and drop the empty ones.
  2. Split each line into a name, a quantity and a price.
  3. Print a line per item while folding the totals together.
  4. Print the totals.

Further reading

  • Strings
  • Interpolated strings
  • Plain text formatting

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, F#"

printfn "%d" s.Length              // 9
printfn "%c" (s[0])                // H  (a char)
printfn "%s" (s[7..])              // F# (a slice from index 7 to the end)
printfn "%s" (s.Substring(0, 5))   // Hello (start 0, length 5)
printfn "%s" (s.ToUpper())         // HELLO, F#
printfn "%s" ("  padded  ".Trim()) // padded
open System

let words = "red green  blue".Split(' ', StringSplitOptions.RemoveEmptyEntries)
// [| "red"; "green"; "blue" |]

let csv = String.Join(",", words)       // "red,green,blue"
let same = String.concat "," words      // F#'s own version
url.StartsWith "http"
file.EndsWith ".fs"
"banana".Contains "nan"        // true
"banana".IndexOf 'n'           // 2  (-1 if not found)
let item = "apples"
let qty = 12
let line = $"{item}: {qty}"            // "apples: 12"
let price = $"%.2f{3.5}"               // "3.50"
let padded = sprintf "%-8s|%5d" item qty   // "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