F# 将字符串拆分为包含不超过n个字符的字符串的字符串列表

F# 将字符串拆分为包含不超过n个字符的字符串的字符串列表,f#,F#,我有一个长字符串,我需要将其转换为字符串列表,其中列表中的每个字符串都是基于链接到的@Carsten构建的,下面是一个生成字符串列表的版本,而不是像链接示例那样将它们连接在一起: let until index (text:string) = text.[0..index-1] let from index (text:string) = text.[index..] let wrap fullText lineLength = let untilLineLength

我有一个长字符串,我需要将其转换为字符串列表,其中列表中的每个字符串都是基于链接到的@Carsten构建的,下面是一个生成字符串列表的版本,而不是像链接示例那样将它们连接在一起:

let until index (text:string) =
    text.[0..index-1]

let from index (text:string) =
    text.[index..]

let wrap fullText lineLength =
    let untilLineLength = until lineLength
    let rec wrapRecursive (text:string) existingLines =
        if text.Length <= lineLength then
            (List.rev ((text.Trim())::existingLines)) //|> String.concat "\n"
        else
            let wrapIndex,nextLineIndex =
                match (text |> untilLineLength).LastIndexOf(" ") with
                | -1 -> lineLength, lineLength
                | spaceIndex -> spaceIndex, spaceIndex + 1
            ((text |> until wrapIndex).Trim())::existingLines |> wrapRecursive (text |> from nextLineIndex) 

    wrapRecursive fullText List.empty
产出:

[“什么河流从黑森林中升起,流过”;“穿过铁” 门,然后倒入黑色的“;“海?”]


到目前为止你试过什么?你能展示一下你解决这个问题的尝试吗?我来自C#背景,我的尝试到处都是,非常不实用。这就是为什么我没有发布代码,因为那样只会污染问题。我开始做一个非常手动的一步一步的方法,将字符串拆分为单词(实际上是strtok),然后迭代列表中的每个字符串,将每个子字符串添加到临时字符串中,直到其长度达到50个字符,然后将该临时字符串添加到我的返回字符串中。不管怎么说,这一切都很丑陋;因此,我希望有人能教我正确的方法,我相信没有一种“正确”的方法。在这种情况下,我会修改问题来描述您想要什么样的解决方案:最短、最快等。这是一个众所周知的问题;)。。。。启动你最喜欢的搜索引擎,寻找“word wrap kata”-你会找到很多你想要的语言的解决方案;)(例如)工作得很好。谢谢
let until index (text:string) =
    text.[0..index-1]

let from index (text:string) =
    text.[index..]

let wrap fullText lineLength =
    let untilLineLength = until lineLength
    let rec wrapRecursive (text:string) existingLines =
        if text.Length <= lineLength then
            (List.rev ((text.Trim())::existingLines)) //|> String.concat "\n"
        else
            let wrapIndex,nextLineIndex =
                match (text |> untilLineLength).LastIndexOf(" ") with
                | -1 -> lineLength, lineLength
                | spaceIndex -> spaceIndex, spaceIndex + 1
            ((text |> until wrapIndex).Trim())::existingLines |> wrapRecursive (text |> from nextLineIndex) 

    wrapRecursive fullText List.empty
let fullText = "What river rises in the Black Forest, flows through the Iron Gate, and empties into the Black Sea?"

let lineLength = 50

let res = lineLength |> wrap fullText

printfn "%A" res