Split
A string
contains many values. It has names of animals separated by commas. We must split this string
. Splitting is not exciting, but it is useful.
With Split
, a method on the String
type in .NET, we receive a String
array. And with the helpful Seq.toList
we can convert this into an F# list for further use.
We introduce a string
with three fields separated by commas. We call the Split
method with a single comma char
—this is expanded to a char
array.
string
array from Split
containing 3 elements. We use a for-in
loop to display them to the screen.let animals = "bear,frog,eagle" // Split on the comma. // ... This is creating a single-element character array for us. let result = animals.Split ',' // Loop over and display strings. for value in result do printfn "%A" value"bear" "frog" "eagle"
Seq.toList
This example adds some complexity. We introduce a splitLine
function. This receives a string
and calls Split
on it. Then it returns the result of Seq.toList
.
splitLine
on a string
, we can access the data in an F# list.// Create a splitLine function. // ... It uses Seq.toList on the result of line.Split. // So we can access a list. let splitLine = (fun (line : string) -> Seq.toList (line.Split ',')) // Split this line into a list. let plants = "turnip,carrot,lettuce" let result = splitLine plants // Display our results in a for-loop. for value in result do printfn "%A" value"turnip" "carrot" "lettuce"
String
separatorWith Split()
we can separate a string
based on a substring delimiter. We create a string
array containing all delimiters and pass it to Split
.
RemoveEmptyEntries
is part of the System
namespace. With it, empty array elements are removed before Split
returns.string
has an empty string
between 2 delimiters. But this is not part of the result.open System let items = "keyboard; mouse; ; monitor" // Call split with a string array as the first argument. // ... This splits on a two-char sequence. // Also remove empty array elements. let result = items.Split([|"; "|], StringSplitOptions.RemoveEmptyEntries) // Print all elements in the array with Seq.iter. Seq.iter (fun x -> printfn "%A" x) result"keyboard" "mouse" "monitor"
Here we Split
on 2 different character delimiters. We provide a char
array to Split()
as the first argument. We use a for
-loop to print results.
let clothes = "pants.shoes:socks" // Split on two different characters. let result = clothes.Split([|'.'; ':'|]) // Print results with for-loop. for r in result do printfn "%s" rpants shoes socks
F# adds no special splitting methods. But it allows easy access to the powerful .NET Framework string
split method. With some conversion, we can split into a list.