F#, Split String and .Net methods
35,898
Solution 1
You call them as instance methods:
let Count (text : string) =
let words = text.Split [|' '|]
let nWords = words.Length
(nWords)
(Note you need to use [| |]
because Split takes an array not a list; or, as per Joel Mueller's comment, because Split takes a params array, you can just pass in the delimiters as separate arguments (e.g. text.Split(' ', '\n')
).)
Solution 2
The function String.split is now defined in the F# Power Pack. You must add
#r "FSharp.PowerPack.dll";;
#r "FSharp.PowerPack.Compatibility.dll";;
See the errata for Expert F#: http://www.expert-fsharp.com/Updates/Expert-FSharp-Errata-Jan-27-2009.pdf
Get FSharp.PowerPack.dll here: http://fsharppowerpack.codeplex.com/
Related videos on Youtube
Comments
-
Neo almost 4 years
I'm new to F#. I'm using VS2008 shell and F# interactive. I try to split a string using "System.String.Split" but then I get the error: "Split is not a static method"
code example:
let Count text = let words = System.String.Split [' '] text let nWords = words.Length (nWords)
How do I use the String methods like split in F# ?
-
Joel Mueller about 14 yearsSplit takes a params array, which means you can pass in an array, or you can simply pass in one or more character literals, without an array.
text.Split ' '
ortext.Split ' ', '\n'
(with or without parens) are perfectly valid. -
kvb about 14 years@Joel - Your second example doesn't work; it creates a tuple with
'\n'
as the second half. It does work when called astext.Split(' ', '\n')
, though. -
Joel Mueller about 14 years@kvb - You're right, I misread the output in FSI. I was surprised when it seemed to work.