F# String Examples:

Understand strings and string methods. Use .NET Framework methods in F# constructs.

Strings. In F# we use .NET Framework string methods like IndexOf and ToLower. We call these methods within functional constructs.

String notes. With we can apply a mapping to all characters in a string. A lambda expression is used. We can chain string manipulations together in a pipeline.

First example. This example adds three string functions. In uppercase() it calls ToUpper. In addGreeting and addComma it adds some surrounding text to a string.

Let: In the "let result" statement we pipeline the three methods together with a name argument (with value "visitor").

Result: The three functions handle the string in order and the resulting text has been processed as expected.

F# program that uses strings // Three string manipulation functions. let uppercase (x : string) = x.ToUpper() let addGreeting (x : string) = "Hi " + x let addComma (x : string) = x + "," // Used to compute result. let name = "visitor" // Apply three string functions with pipeline operator on the name. let result = name |> uppercase |> addGreeting |> addComma // Write result. printfn "%A" result Output "Hi VISITOR," In F# we find a function that changes each character in a string according to a function argument. We use upperMap here to uppercase only the letters "a" and "z."Fun

Match: We use pattern-matching in the upperMap function to determine how to modify the letter.


Tip: With we have an effective way to translate strings. For something like a ROT13 transformation this is ideal.

F# program that uses let value = "abcxyz" // This function only uppercases 2 letters. let upperMap = fun c -> match c with | 'a' -> 'A' | 'x' -> 'X' | _ -> c // Apply our upperMap function with let result = upperMap value printfn "%A" result Output "AbcXyz"

Methods. With F# we can invoke string methods from the .NET Framework. Some of the top methods are Split, IndexOf, Replace. These help us make programs that actually do things.IndexOfSplitReplace

Parse, convert int. With Int32.TryParse, we can convert a string to an int. No custom parsing logic is needed. The F# language requires special syntax here.Int32.TryParse

Ciphers, ROT13. With the ROT13 cipher, we rotate (shift) characters 13 places. We learn character-based manipulation of strings. With F# we employ the function.ROT13

Strings are everywhere. We use them in almost all programs, even functional F# ones. With the heavily-tested, fast string methods from .NET, we have a powerful string solution.
Dot Net Perls
© 2007-2020 Sam Allen. Every person is special and unique. Send bug reports to