Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

F# Convert String Array to String

Tags:

string

f#

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#?

ADDED

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

Solution

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 ""
like image 258
prosseek Avatar asked May 27 '11 20:05

prosseek


2 Answers

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)
like image 186
desco Avatar answered Nov 18 '22 17:11

desco


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#.

like image 6
phoog Avatar answered Nov 18 '22 17:11

phoog