Fsharp: Convert String
Convert string to int, float, byte array
Convert string to int
// string to int printfn "%O" ((int "123").GetType()) // System.Int32
Convert string to float
// string to float printfn "%O" ((float "3.4").GetType()) // System.Double
Convert string to byte array
// string to byte array printfn "%O" ("abc"B .GetType()) // System.Byte[]
Split string to chars
Split string to ASCII chars
let xtext = "some" let xchars = xtext.ToCharArray() printfn "%A" xchars // [|'s'; 'o'; 'm'; 'e'|] // does not work if your string contain non-ASCII
let xtext = "some 世界" let xcharsSeq: seq<char> = xtext printfn "%A" xcharsSeq // "some Σ╕ûτòî" // does not work if your string contain non-ASCII
Split string to Unicode chars
open System let xtext = "🦋café" printfn "%A" (xtext .EnumerateRunes() |> Seq.map string) // seq ["🦋"; "c"; "a"; "f"; ...] printfn "%A" (xtext .EnumerateRunes() |> Seq.map string |> Seq.toList) // ["🦋"; "c"; "a"; "f"; "é"]
let xtext = "hello世界👨🚀" // 2. char seq (very idiomatic in F# — lazy, composable) let charsSeq: seq<char> = xtext // string implements seq<char> directly! // 3. char list (if you really want an immutable list) let charsList: char list = xtext |> List.ofSeq // or Seq.toList xtext // or more explicit: let charsList2 = xtext.ToCharArray() |> Array.toList // 4. As array using array comprehension (less common) let charsArray3 = [| for c in xtext -> c |] // 5. If you want to treat it as a sequence and do something with it immediately let example = xtext |> Seq.map (fun c -> System.Char.ToUpper c) |> Seq.toArray