String Examples: String.mapUnderstand strings and string methods. Use .NET methods in F# constructs.
This page was last reviewed on Feb 23, 2023.
Strings. In the F# language we use .NET string methods like IndexOf and ToLower. We call these methods within functional constructs.
String notes. With String.map 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.
Detail In the "let result" statement we pipeline the three methods together with a name argument (with value "visitor").
Result The 3 functions handle the string in order and the resulting text has been processed as expected.
// 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
String.map. In F# we find a String.map 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."
Detail We use pattern-matching in the upperMap function to determine how to modify the letter.
Tip With String.map we have an effective way to translate strings. For something like a ROT13 transformation this is ideal.
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 String.map. let result = String.map upperMap value printfn "%A" result
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.
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.
Ciphers, ROT13. With the ROT13 cipher, we rotate (shift) characters 13 places. We learn character-based manipulation of strings. With F# we employ the String.map function.
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 is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Feb 23, 2023 (edit).
© 2007-2023 Sam Allen.