如何将字符列表更改为字符串?

时间:2009-11-19 19:44:48

标签: string f#

在F#中,我想将字符列表转换为字符串。请考虑以下代码:

let lChars = ['a';'b';'c']

如果我只是做 lChars.ToString ,我会得到“['a';'b';'c']”。我想要“abc”。我意识到我可能会做一个List.reduce来获得我正在寻找的效果,但似乎应该有一些原始内置到库中来执行此操作。

为了给出一点上下文,我正在对字符串中的单个字符进行一些操作,当我完成后,我想显示结果字符串。

我试过用谷歌搜索这个并没有那样的快乐。我是否需要咬紧牙关并构建一个List.reduce表达式来进行这种转换,还是有一些更优雅的方法来做到这一点?

7 个答案:

答案 0 :(得分:29)

你试过吗

System.String.Concat(Array.ofList(lChars))

答案 1 :(得分:6)

你可以用多少种方法在F#中构建一个字符串? 这是另一小撮:

let chars = ['H';'e';'l';'l';'o';',';' ';'w';'o';'r';'l';'d';'!']

//Using an array builder
let hw1 = new string [|for c in chars -> c|]

//StringBuilder-Lisp-like approach
open System.Text
let hw2 = 
    string (List.fold (fun (sb:StringBuilder) (c:char) -> sb.Append(c)) 
                      (new StringBuilder())
                       chars)

//Continuation passing style
let hw3 =
    let rec aux L k =
        match L with
        | [] -> k ""
        | h::t -> aux t (fun rest -> k (string h + rest) )
    aux chars id

编辑:时间可能很有趣?我将hw1..3转换为函数,并为它们提供了500000个随机字符列表:

  • hw1:51ms
  • hw2:16ms
  • hw3:呃......长得够长胡子?我认为它只是吃掉了我的所有记忆。

答案 2 :(得分:4)

这里没有看到这个,所以:

let stringFromCharList (cl : char list) =
    String.concat "" <| List.map string cl

“”只是一个空字符串。

FSI输出:

> stringFromCharList ['a'..'d'];;
val it : string = "abcd"

编辑:

不喜欢这种语法回到这里,所以这里有一个更具规范性的功能:

['a'..'z'] |> List.map string |> List.reduce (+)

答案 3 :(得分:2)

['a';'b';'c'] |> List.fold_left (fun acc c -> acc ^ (string c)) ""

编辑: 这是另一种有趣的方式来完成你的任务:

type t =
  | N
  | S of string
  static member Zero
    with get() = N
  static member (+) (a: t, b: t) = 
    match a,b with
      | S a, S b -> S (a+b)
      | N, _ -> b
      | _, N -> a

let string_of_t = function
  |N -> ""
  |S s -> s

let t_of_char c = S (string c)

['a'; 'b'; 'c'] |> List.map t_of_char |> List.sum |> string_of_t

可悲的是,只使用'Zero'成员扩展System.String不允许将List.sum与字符串一起使用。

编辑(回答Juilet): 是的,你是对的,左折是慢的。但我知道更慢的右折:):

#r "FSharp.PowerPack"

List.fold_right (String.make 1 >> (^)) ['a';'b';'c'] ""

当然有快速而简单的方法:

new System.String(List.to_array ['1';'2';'3'])

答案 4 :(得分:1)

我使用'sprintf'对我来说更容易:

let t = "Not what you might expect"
let r = [ for i in "aeiou" -> i]
let q = [for a in t do if not (List.exists (fun x -> x=a) r) then yield a]
let rec m  = function  [] -> "" | h::t ->  (sprintf "%c" h) + (m t)
printfn "%A"  (m q)

答案 5 :(得分:0)

以下解决方案适合我:

let charList = ["H";"E";"L";"L";"O"]

let rec buildString list = 
    match list with
    | [] -> "" 
    | head::tail -> head + (buildString tail)

let resultBuildString = buildString charList

答案 6 :(得分:0)

    [|'w'; 'i'; 'l'; 'l'|]
    |> Array.map string
    |> Array.reduce (+)

或以其他人的身份发布:

    System.String.Concat([|'w'; 'i'; 'l'; 'l'|])
相关问题