Skip to content
Tutorials Center
My learning

Topics

Lesson 6 of 37 ยท Language Basics

F# Strings: Literals, Interpolation, Slicing and the String Module

Work with F# strings: literals, triple-quoted and verbatim strings, interpolation with format specifiers, sprintf, concatenation, slicing, the String module and .NET string methods.

Text is everywhere, so F# makes strings pleasant. A string is an immutable sequence of characters, the same System.String as in C#. This lesson covers how to write string literals, build text with interpolation and sprintf, slice and search, and use the String module together with the .NET methods you already know.

String literals

FSHARP
let plain = "Hello, F#"
let withEscapes = "Line 1\nLine 2\tTabbed \"quoted\""
let verbatim = @"C:\temp\notes.txt"        // backslashes are literal
let triple = """He said "hi" and left"""    // quotes need no escaping
let multi = "first
second"                                       // newlines allowed inside

Triple-quoted strings are great for JSON, SQL and anything with many quotes. To split a long literal across lines without a newline, end the line with a backslash.

Concatenation

Use + or the ^ operator (older style). Prefer interpolation for anything with more than two pieces.

FSHARP
let full = "Ada" + " " + "Lovelace"
let repeated = String.replicate 3 "ab"      // "ababab"
let joined = String.concat ", " [ "a"; "b"; "c" ]   // "a, b, c"

Interpolated strings

Put a $ before the opening quote and write expressions in braces:

FSHARP
let name = "Ada"
let age = 36
let msg = $"{name} is {age} years old"
let math = $"2 + 3 = {2 + 3}"
let padded = $"|{name,10}|{name,-10}|"      // right and left alignment
let money = $"Total: {1234.5:F2}"           // .NET format specifier
let pct = $"{0.256:P1}"                     // percent
  • After a comma you give a width (negative means left-aligned).
  • After a colon you give a .NET format string such as F2, N0, P1, yyyy-MM-dd.
  • To print a literal brace, double it: {{ and }}.

F# also has typed interpolation: write a printf-style specifier before the expression, as in $"%d{age}", and the compiler checks that age is an integer.

sprintf and printf specifiers

sprintf is the type-safe string builder you met in Your first F# program:

FSHARP
let line = sprintf "%-8s|%5d|%8.2f" "apple" 3 1.5
// "apple   |    3|    1.50"

Flags: - left align, 0 zero pad (%05d gives 00042), + always show the sign. Because sprintf returns a function until all arguments are supplied, you can partially apply it:

FSHARP
let greet = sprintf "Hello, %s!"
let a = greet "Ada"
let b = greet "Grace"

Length, indexing and slicing

FSHARP
let s = "Functional"
printfn "%d" s.Length          // 10
printfn "%c" s.[0]             // F
printfn "%c" (s[1])            // u (the dot is optional in F# 6+)
printfn "%s" (s[0..3])        // Func
printfn "%s" (s[4..])         // tional
printfn "%s" (s[..2])         // Fun

Slices include both ends: s[0..3] is four characters. An out-of-range slice returns an empty string rather than throwing, but an out-of-range index like s[99] raises an exception.

The String module

The String module holds functions made for pipelines:

Trimming, splitting and case changes are .NET methods (shown below). The module offers these functions, all pipeline friendly:

Function Example Result
String.length String.length "abc" 3
String.map String.map System.Char.ToUpper "abc" "ABC"
String.filter String.filter System.Char.IsDigit "a1b2" "12"
String.forall / String.exists String.exists System.Char.IsDigit "a1" true
String.replicate String.replicate 2 "xy" "xyxy"
String.concat String.concat "-" ["a";"b"] "a-b"
String.collect String.collect (fun c -> string c + string c) "ab" "aabb"
String.init String.init 3 string "012"

For everything else, call the .NET methods directly: they work on every F# string.

FSHARP
let text = "  The quick brown fox  "
printfn "[%s]" (text.Trim())
printfn "%s" (text.ToUpper())
printfn "%b" (text.Contains "quick")
printfn "%s" (text.Replace("quick", "slow"))
printfn "%A" (text.Trim().Split ' ')
printfn "%b" (text.StartsWith "The")
printfn "%d" (text.IndexOf "brown")

Split ' ' produces [|"The"; "quick"; "brown"; "fox"|].

Strings are sequences of chars

Because a string is a seq<char>, you can use collection functions on it:

FSHARP
let vowels = "functional programming" |> Seq.filter (fun c -> "aeiou".Contains c) |> Seq.length
let reversed = "stressed" |> Seq.rev |> Seq.toArray |> System.String

reversed is "desserts". Notice the last step: System.String is used here as a constructor function taking a char[].

Comparing strings

= compares strings by value, case-sensitively. For other comparisons use String.Equals with a comparison mode:

FSHARP
let same = "abc" = "ABC"                                              // false
let ignoreCase = System.String.Equals("abc", "ABC", System.StringComparison.OrdinalIgnoreCase)  // true

Runnable stand-ins in C#

C# supports the same interpolation and format specifiers, so these runs preview what $"..." does in F#.

C# C# stand-in: interpolation with width and format

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

C# C# stand-in: slicing and searching

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

C# ranges are end-exclusive (s[..4] is four characters), whereas F# slices are end-inclusive (s[0..3]). That difference is worth remembering when you port code.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is "Functional"[0..3] in F#?

    F# slices include both the start and the end index, so indices 0 to 3 give four characters.
  2. 2. How do you put a literal opening brace in an interpolated string?

    Doubling the brace, {{, produces a literal brace.
  3. 3. What does $"|{name,-10}|" do?

    A negative width after the comma left-aligns the value.
  4. 4. Which literal is best for text containing many double quotes?

    Triple-quoted strings allow quotes without escaping.

Summary

  • Strings are immutable .NET strings; use normal, verbatim (@"...") and triple-quoted literals.
  • Interpolation $"{x}" supports widths and .NET format strings; sprintf is the type-checked alternative and can be partially applied.
  • Slices are end-inclusive: s[0..3] gives four characters.
  • The String module and the .NET string methods both work; strings can also be treated as sequences of char.

Next: Operators and type conversion