String Functions in F#
Our first program demonstrates various string operations using F#’s built-in String module. Here’s the full source code:
open System
// We alias printfn to a shorter name as we'll use it a lot below.
let p = printfn
[<EntryPoint>]
let main argv =
// Here's a sample of the functions available in the String module.
// Since these are functions from the module, not methods on the string
// object itself, we need to pass the string in question as the first
// argument to the function. You can find more functions in the
// String module documentation.
p "Contains: %b" (String.contains "es" "test")
p "Count: %d" (Seq.filter ((=) 't') "test" |> Seq.length)
p "StartsWith: %b" (String.startsWith "te" "test")
p "EndsWith: %b" (String.endsWith "st" "test")
p "IndexOf: %d" ("test".IndexOf('e'))
p "Join: %s" (String.concat "-" ["a"; "b"])
p "Repeat: %s" (String.replicate 5 "a")
p "Replace: %s" ("foo".Replace("o", "0"))
p "Replace: %s" ("foo".Replace("o", "0", 1, System.StringComparison.Ordinal))
p "Split: %A" ("a-b-c-d-e".Split('-'))
p "ToLower: %s" (String.lowercase "TEST")
p "ToUpper: %s" (String.uppercase "test")
0
To run the program, save the code in a file with a .fs
extension (e.g., StringFunctions.fs
) and use the F# compiler (fsc
) to compile it, then run the resulting executable:
$ fsharpc StringFunctions.fs
$ mono StringFunctions.exe
Contains: true
Count: 2
StartsWith: true
EndsWith: true
IndexOf: 1
Join: a-b
Repeat: aaaaa
Replace: f00
Replace: f0o
Split: [|"a"; "b"; "c"; "d"; "e"|]
ToLower: test
ToUpper: TEST
This example demonstrates various string operations in F#. Note that F# provides both functions in the String
module and instance methods on string objects, giving you flexibility in how you work with strings.
F# doesn’t have a direct equivalent to Go’s strings
package, but it provides similar functionality through the String
module and instance methods on strings. Some operations, like Count
, are implemented using more general sequence operations in F#.
The String
module in F# provides many useful string-related functions. You can find more functions in the String module documentation.