How do I split a string into a list of characters in F Sharp

How to split a string into a list of characters in F sharp, for example, if I want to split the word "Hello" into a list of characters, i.e.

"Hello" ->['H';'e';'l';'l';'o']

I tried Split ([| |]) , but it only breaks the string depending on the u pass parameter.

I tried this but it still didn't work

let splitChar (text:string) = 
    [for c in text ->c] 

let splitChar (text:string) = 
    [for c in text do yield c] 
+7
source share
4 answers

You can use Seq.toListto convert a string to a list of characters:

Seq.toList "Hello"
+12
source

, IEnumerable<char>. char. Chars.

Seq , :

"abc" |> Seq.iter (fun x->printfn "%c" x)

:

"abc" |> String.iter (fun x->printfn "%c" x)

String String . , String.length String.Length, , Seq:

    let length (str:string) =
        let str = emptyIfNull str
        str.Length

, String.iter Chars :

    let iter (f : (char -> unit)) (str:string) =
        let str = emptyIfNull str
        for i = 0 to str.Length - 1 do
            f str.[i] 
+5

.NET String.ToCharArray. , String (Char []) , F # .

"Hello".ToCharArray() |> List.ofArray

It might be better to use only the F # Array module. I guess it is List.ofArraymore effective than List.ofSeq. If that doesn't matter, like Chad's answer, then the F # idiomatic way:

"Hello" |> List.ofSeq
0
source

I noticed cases where at first I would think of splitting something into an array of characters or a list at the beginning, but where should I be more concise.

let msg = "hello-world"

let resultA = 
    msg.[0..0].ToUpper() + msg.[1..].Replace('-', ' ')

let resultB = 
    Seq.toList (msg)
    |> (fun list -> (string list.Head).ToUpper() + (String.Concat(list.Tail)).Replace('-', ' '))

// val resultA : string = "Hello world"
// val resultB : string = "Hello world"

I find the path "resultA" nicer.

0
source

Source: https://habr.com/ru/post/1684455/


All Articles