简体   繁体   English

在F#中乘以一个字符串

[英]Multiplying a string in F#

I have a question I am rather unsure about. 我有一个我不太确定的问题。

My questions is as follows 我的问题如下

let myFunc (text:string) (times:int) = ....

What I want this function to do is put the string together as many times as specified by the times parameter. 我希望这个函数做的是将字符串放在一起,与times参数指定的times一样多。

if input = "check " 3 I want the output string = "check check check" if input = "check " 3我想输出字符串= "check check check"

I have tried with a loop, but couldn't seem to make it work. 我试过一个循环,但似乎无法使它工作。

Anyone? 任何人?

Actually the function is already in String module: 实际上该函数已经在String模块中:

let multiply text times = String.replicate times text

To write your own function, an efficient way is using StringBuilder : 要编写自己的函数,一种有效的方法是使用StringBuilder

open System.Text

let multiply (text: string) times =
    let sb = new StringBuilder()
    for i in 1..times do
        sb.Append(text) |> ignore
    sb.ToString()

If you want to remove trailing whitespaces as in your example, you can use Trim() member in String class to do so. 如果要删除示例中的尾随空格,可以使用String类中的Trim()成员来执行此操作。

If you want a pure functional "do-it-yourself" version for F# learning purposes, then something like the following snippet will do: 如果您想要一个纯粹的功能性“自己动手”版本用于F#学习目的,那么类似下面的代码片段将会:

let myFunc times text =
    let rec grow result doMore =
        if doMore > 0 then
            grow (result + text) (doMore- 1)
        else
            result
    grow "" times

Here is the test: 这是测试:

> myFunc 3 "test";;
val it : string = "testtesttest"

Otherwise you should follow the pointer about the standard F# library function replicate given in pad's answer. 否则,您应该按照pad的答案中给出的关于标准F#库函数replicate的指针。

A variation on pad's solution, given that it's just a fold: pad的解决方案的一个变种,因为它只是一个折叠:

let multiply n (text: string) = 
  (StringBuilder(), {1..n})
  ||> Seq.fold(fun b _ -> b.Append(text))
  |> sprintf "%O"

String.replicate already provides the functionality you're looking for. String.replicate已经提供了您正在寻找的功能。

If for some reason you want the arguments reversed, you can do it as follows: 如果由于某种原因你希望反转的参数,你可以这样做:

(* A general function you should add to your utilities *)
let flip f a b = f b a

let myFunc = flip String.replicate

In a simple recursive fashion: 以简单的递归方式:

let rec dupn = function
|s,1 -> s
|s,n -> s ^ dupn(s, n-1)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM