如何解决F#将字符串数组转换为字符串
| 使用C#,我可以使用string.Join(\"\",lines)
将字符串数组转换为字符串。
我该怎么办才能用F#做同样的事情?
添加
我需要从文件中读取行,执行一些操作,然后将所有行连接为一行。
当我运行这段代码
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)
我得到这个错误
error FS0039: The value or constructor \'Join\' is not defined
我尝试了此代码“ 3”来获取此错误
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(\"{\",\"}}\"),1) + @\"\\n\"|]
let concatenatedLine = String.Join(\"\",lines)
File.WriteAllText(\"tclscript.txt\",concatenatedLine)
而且这也有效。
let concatenatedLine = lines |> String.concat \"\"
解决方法
使用String.concat吗?
[\"a\"; \"b\"]
|> String.concat \",\" // \"a,b\"
编辑:
在您的代码中,将File.WriteAllLines替换为File.WriteAllText
let concatenatedLine =
[\"a\"; \"b\"]
|> String.concat \",\"
open System.IO
let path = @\"...\"
File.WriteAllText(path,concatenatedLine)
, 从fsi控制台窗口复制:
> open System;;
> let stringArray = [| \"Hello\"; \"World!\" |];;
val stringArray : string [] = [|\"Hello\"; \"World!\"|]
> let s = String.Join(\",\",stringArray);;
val s : string = \"Hello,World!\"
>
编辑:
与使用F#核心库中的String.concat相比,使用.NET框架类库中的String.Join当然要少一些习惯。我只能假定这就是为什么有人否决了我的答案的原因,因为那个人没有扩大解释投票的礼貌。
正如我在下面的评论中提到的那样,我发布此答案的原因是,在所有其他答案中使用String.concat可能会误导普通读者以为String.Join在F#中根本不可用。
, List.ofSeq \"abcd\" |> List.toArray |> (fun s -> System.String s) |> printfn \"%A\"
List.ofSeq \"abcd\" |> List.toArray |> (fun s -> new System.String(s)) |> printfn \"%A\"
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。