把从文件中读出的字符串连接起来

时间:2021-06-12 04:20:35
把从文件中读出的字符串连接起来:

let f = File.ReadAllLines (@"C:\Users\w1\Desktop\123.txt");;
String.concat "," f;;

但是,对于空行,比较难处理:

let g = Array.fold (fun a (e:string) ->if  String.IsNullOrWhiteSpace (e.Trim()) then a else a + e.Trim() + "," ) ""  f;;

即使这样做了,最后还会有一个分隔符:
val it : string = "123,456,789,"

===========
如果读取的文件中有汉字,需要 ReadAllLines 的第二个参数:

// File.ReadAllLines (d.FileName, System.Text.Encoding.GetEncoding(936));;
// File.ReadAllLines (d.FileName, System.Text.Encoding.Default);;

==========
去掉最后的逗号:

let h = g.Substring(0, g.Length-1);;


=============
这个可能比较完美了:
    let f = (File.ReadAllLines (@"e:\projects\123.txt",Text.Encoding.GetEncoding(936)))
            |> Array.choose(fun e -> if String.IsNullOrWhiteSpace (e) then None else Some(e.Trim()))


    Console.WriteLine (String.Join (",", f ))