Ivan
Ivan

Reputation: 785

How do I split a string into a List of chars in F sharp

How do I split string into a list of chars in F sharp for example if I want to split the word "Hello" into a list of chars ie.

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

I have tried Split([| |]) but it only splits a string depending on the parameter u pass in.

I have tried this to but it still did not work

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

let splitChar (text:string) = 
    [for c in text do yield c] 

Upvotes: 28

Views: 20565

Answers (4)

Tom Ell
Tom Ell

Reputation: 215

I've noticed occasions where I would initially think to split something into a char array or a list first - but where I should be more succinct.

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"

The 'resultA' way is nicer I think.

Upvotes: 5

Cameron Taggart
Cameron Taggart

Reputation: 6091

In .NET, you can use String.ToCharArray method. To get back into a String, you can use String(Char[]) now that F# using constructors as functions.

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

It may be better performance to just use the F# Array module. I'm guessing List.ofArray is more efficient than List.ofSeq. If that doesn't matter, similar to Chad's answer, the F# idiomatic way is:

"Hello" |> List.ofSeq

Upvotes: 6

Panagiotis Kanavos
Panagiotis Kanavos

Reputation: 131247

A string is essentially a sequence of characters, as it implements IEnumerable<char>. Internally, a string is an array of char values. That array is exposed through the Chars indexer.

You can use any Seq method on a string, eg :

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

Individual characters are also available

You can also use the optimized functions of the String module :

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

The String module uses the methods of the String class to improve performance. For example, the String.length function is an alias for the String.Length property, so it doesn't have to iterate over all characters like Seq would do:

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

Other functions, like String.iter use the Chars indexer directly :

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

Upvotes: 14

Chad Gilbert
Chad Gilbert

Reputation: 36375

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

Seq.toList "Hello"

Upvotes: 33

Related Questions