With C#, I can use string.Join("", lines)
to convert string array to string.
What can I do to do the same thing with F#?
I need to read lines from a file, do some operation, and then concatenate all the lines into a single line.
When I run this code
open System.IO
open String
let lines =
let re = System.Text.RegularExpressions.Regex(@"#(\d+)")
[|for line in File.ReadAllLines("tclscript.do") ->
re.Replace(line.Replace("{", "{{").Replace("}", "}}").Trim(), "$1", 1)|]
let concatenatedLine = String.Join("", lines)
File.WriteAllLines("tclscript.txt", concatenatedLine)
I got this error
error FS0039: The value or constructor 'Join' is not defined
I tried this code let concatenatedLine = lines |> String.concat ""
to get this error
error FS0001: This expression was expected to have type
string []
but here has type
string
open System.IO
open System
let lines =
let re = System.Text.RegularExpressions.Regex(@"#(\d+)")
[|for line in File.ReadAllLines("tclscript.do") ->
re.Replace(line.Replace("{", "{{").Replace("}", "}}"), "$1", 1) + @"\n"|]
let concatenatedLine = String.Join("", lines)
File.WriteAllText("tclscript.txt", concatenatedLine)
and this one also works.
let concatenatedLine = lines |> String.concat ""
use String.concat ?
["a"; "b"]
|> String.concat ", " // "a, b"
EDITED:
in your code replace File.WriteAllLines with File.WriteAllText
let concatenatedLine =
["a"; "b"]
|> String.concat ", "
open System.IO
let path = @"..."
File.WriteAllText(path, concatenatedLine)
Copied from an fsi console window:
> open System;;
> let stringArray = [| "Hello"; "World!" |];;
val stringArray : string [] = [|"Hello"; "World!"|]
> let s = String.Join(", ", stringArray);;
val s : string = "Hello, World!"
>
EDIT:
Using String.Join from the .NET framework class library is, of course, less idiomatic than using String.concat from the F# core library. I can only presume that is why someone voted my answer down, since that person did not extend the courtesy of explaining the vote.
The reason I posted this answer, as I mentioned in my comment below, is that the use of String.concat in all of the other answers might mislead casual readers into thinking that String.Join is not at all available in F#.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With