Creating substrings in F#

Reading a chunk of a string into another string is based on the position of the characters in the string. The characters in the string form an array of chars and we can read parts of it by referring to the required array positions of the characters. This is no different from popular OOP languages like C# and Java. The only difference is the syntax.

Let’s start with the following string:

let longString = "The message couples the distressed heat before a purchase."

The random sentence generator site has a lot of similar meaningless sentences for testing.

The most simplistic application of substrings is to read one character:¨

let longString = "The message couples the distressed heat before a purchase."
let singleChar = longString.[5]

singleChar will be ‘e’ since it has position 5 in a 0 based array in the string: T-h-e-whitespace-m-e, that’s position 0, 1, 2, 3, 4 and 5 respectively. Note how the array element selector must be connected with the string using a dot.

The selector can accept a range like here:

let longString = "The message couples the distressed heat before a purchase."
let substring = longString.[20..]

This selects the string from position 20 to the end, i.e. “the distressed heat before a purchase.”.

Conversely we can only provide the last position:

let longString = "The message couples the distressed heat before a purchase."
let substring = longString.[..18]

…which gives “The message couples”.

Finally we can provide both the start and end position:

let substring = longString.[4..10]

…which will be equal to “message”.

View all F# related articles here.

Unknown's avatarAbout Andras Nemes
I'm a .NET/Java developer living and working in Stockholm, Sweden.

Leave a comment

Elliot Balynn's Blog

A directory of wonderful thoughts

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog

WEB APPLICATION DEVELOPMENT TUTORIALS WITH OPEN-SOURCE PROJECTS

Once Upon a Camayoc

ARCHIVED: Bite-size insight on Cyber Security for the not too technical.