F# Strings

F# strings are represented as Unicode character arrays, and F# comes with a very rich set of functions that allow you to work with strings such as concatenation, substring extraction, regular expression matching, and more.

F# includes a number of useful features, such as pattern matching and type inference, which make it both easy and efficient to work with F# strings.

This article will introduce some of F# string manipulation features, including Unicode support, string concatenation, string formatting, parsing, and matched regular expressions to match patterns.



F# String Literals

Literals in string form are delimited by quotation marks  to indicate that they are strings.

A number of special characters are used for specific purposes, such as newlines, tabs etc.

Using the backslash \ character, they are encoded. Backslashes are used as part of the escape sequence, along with its related character.

Below is a table of F#’s escape sequences.

CharactersEscape sequences
Backspace\b
Newline\n
Carriage return\r
Tab\t
Backslash\\
Quotation mark\”
Apostrophe\’
Unicode character\uXXXX or \UXXXXXXXX (where X indicates a hexadecimal digit)

Ignore Escape Sequence

Compilers can ignore escape sequences in two different ways, as shown below:

  • By using the @ symbol.
  • Put a triple quote  “‘ around the string.

The @ symbol precedes a string literal, which is called a verbatim string. This way, all escape sequences in the string are ignored, with the exception of two quotation mark characters being interpreted as a single quotation mark character.

Whenever a string is enclosed in triple quotation marks, all escape sequences, including the double quotation marks, are ignored, which means that all escape sequences are ignored.

Example

Using the following example, we will demonstrate how to use this technique when dealing with structures containing embedded quotation marks in XML or other languages:

Example: 

let data = @"<user firstname = ""Jennifer"" lastname = ""Anniston"">" printfn "%s" data

The output of the following example can be seen as follows:

<user firstname = "Jennifer" lastname = "Anniston">

F# Strings Operators

Strings are the sequences of characters that make up a program.

There are many basic operators on strings that can be used to manipulate strings in programming languages.

Among the most common basic operators that can be used on strings are the following:

ValueOverview
collect : (char → string) → string → stringThe purpose of this function is to create a string whose characters are the result of appending a specified function to the characters in the input string and producing a new string. A concatenated string is created as a result.
concat : string → seq<string> → stringBy concatenating the strings with a separator, this method returns a new string which contains all of those strings combined.
exists : (char → bool) → string → boolThe function determines whether any character in the string meets the predicate given by the user.
forall : (char → bool) → string → boolThis function determines whether all characters in the string satisfy the predicate given in the input string.
init : int → (int → string) → stringThis method will create a new string which will contain characters created by applying a predefined function to each index and concatenating the resulting strings together to form the new string.
iter : (char → unit) → string → unitEach character in the string will be applied with the specified function.
iteri : (int → char → unit) → string → unitThis function can be applied to each index of a character in a string as well as to the character itself according to a specification.
iteri : (int → char → unit) → string → unitA string’s length is returned by this method.
map : (char → char) → string → stringIn this function, the input string is converted into a new string with characters whose values are determined based on the application of a specified function to each value within the string.
mapi : (int → char → char) → string → stringIn this method, the characters in the input string are replaced with the results of applying a specified function to each of the characters and indexes within the input string to produce a new string.
replicate : int → string → stringAn instance of a string is concatenated with the specified number of instances of another string to return a string.

Here are a few examples of how some of the above functionalities can be used in the following scenarios:

F# String.collect

String.collect is used to create a string from the input character string by applying a specified function to all the characters of that string to create a new string whose characters result from the application of that function. As a result of this, a string has been concatenated.

Example: 

let stringCollect inputString = String.collect (fun c -> sprintf "%c – " c) inputString printfn "%s" (stringCollect "mrexamples")

The following is the output that you will receive once you have compiled and executed the program:

F# Strings Operators examples


F# String.concat

Using String.concat, you can concatenate a sequence of strings with a separator and return a new string after concatenating the strings.

Example: 

let firstName = "Michael" let lastName = "Jordan"let fullName = String.concat " " [firstName; lastName] printfn "Hello %s!" fullName

The output of the example mentioned above is:

F# String concat examples


F# String.exists

In order to determine whether a substring exists in a given string, we can use the String.exists function.

Example: 

let message = "mrexamples is a great platform to learn programming" let mrexamples= String.exists (fun c -> c = 'm') messageif mrexamples then printfn "The message contains the substring 'mrexamples'." else printfn "The message does not contain the substring 'mrexamples'."

As ‘mrexamples’ is placed in the statement, the output will be:

The message contains the substring ‘mrexamples‘.

F# String.forall

Using String.forall, you can test whether a condition holds for all characters within the string that you are given.

Example: 

let message = "MREXAMPLES"let allUpperCase = String.forall (fun c -> System.Char.ToUpper c) messageif allUpperCase then printfn "All characters in the message are uppercase." else printfn "The message contains lowercase characters."

‘MREXAMPLES’ is in uppercase, therefore the output will be as follows:

All characters in the message are uppercase.

F# String.init

Using String.init, you can construct a new string and apply a function to each index in order to generate a new string.

Example: 

let message = "mrexamples"let reversed = String.init message.Length (fun i -> sprintf " %c " message.[message.Length – i – 1])printfn "Reversed message: %s" reversed
Using String.init function we reversed the string which outputs as follows:
F# String init examples

F# String.iter

If a string contains a series of characters, we can use String.iter to perform a specific action on each one.

Example: 

let message = "mrexamples"String.iter (fun c -> printfn "%c " c) message

Following is the output of the above example to print every character of the string:

m
r
e
x
a
m
p
l
e
s

F# String.iteri

A String.iteri can be used for iterating over every character in a string, as well as its index within the string.

Example: 

let message = "mrexamples"String.iteri (fun i c -> printfn "Char %d is '%c'" i c) message

Here is an example which prints both the character that is being displayed as well as its position within the string:

Char 0 is 'm'
Char 1 is 'r'
Char 2 is 'e'
Char 3 is 'x'
Char 4 is 'a'
Char 5 is 'm'
Char 6 is 'p'
Char 7 is 'l'
Char 8 is 'e'
Char 9 is 's'

F# String.length

The length of a string can be determined by using String.length, which returns an integer of all characters in a string.

Example: 

let message = "mrexamples" let length = message.Length printfn "The lenght of the message is: %d" length

Above example prints the length of the message with the help of length function:

The lenght of the message is: 10

F# String.map

Using String.map, it is possible to apply a given function to every character in a string in order to create a new string with the transformed characters instead of just returning the original strings.

Example: 

let message = "mrexamples!"let reversed = String.map (fun c -> if c = ',' then c else message.[message.Length – 1 – message.IndexOf(c)]) messageprintfn "Original message: %s" message printfn "Reversed message: %s" reversed

Below is an example of the function map() to map string characters and transform instead of returning the original strings.

Original message: mrexamples!
Reversed message: !selp!axerm

F# String.mapi

Using String.mapi, you are able to map a character of a string to a single value, based on the index of the character in the string.

Example: 

let message = "mrexamples" let modifiedMessage = String.mapi (fun i c -> if i % 2 = 0 then System.Char.ToUpper c else c) messageprintfn "Original message: %s" message printfn "Modified message: %s" modifiedMessage

In the above example, the message will be transformed with uppercase characters on every even index:

Original message: mrexamples
Modified message: MrExAmPlEs

F# String.replicate

The method String.replicate can be used to create a new string consisting of repeated characters or strings with a specified number of repetitions.

Example: 

let s = String.replicate 5 "s"printfn "mrexample%s" s

Following example output the replicate of ‘s’ at the end of string

mrexamplesssss

Example Explanation

This F# code creates a new string s by using the String.replicate function to repeat the string “s” five times.

It then prints out a formatted string using printfn that includes the s string concatenated to the end of mrexample.

Here’s a step-by-step explanation of what happens:

  1. String.replicate 5 s creates a new string by repeating the string “s” five times, resulting in the string sssss.
  2. let s = String.replicate 5 s binds the new string to the variable s.
  3. printfn “mrexample%ss prints a formatted string to the console, where %s is a placeholder for the s string. The s string is then concatenated to the end of mrexample to produce the final output: mrexamplesssss.’
We value your feedback.
+1
0
+1
0
+1
0
+1
0
+1
0
+1
0
+1
0

Subscribe To Our Newsletter
Enter your email to receive a weekly round-up of our best posts. Learn more!
icon

Leave a Reply

Your email address will not be published. Required fields are marked *