在F#中乘以字符串 [英] Multiplying a string in F#
问题描述
我有一个不确定的问题.
I have a question I am rather unsure about.
我的问题如下
let myFunc (text:string) (times:int) = ....
我希望此函数执行的操作是将字符串按times
参数指定的次数放置在一起.
What I want this function to do is put the string together as many times as specified by the times
parameter.
if input = "check " 3
我想要输出字符串= "check check check"
if input = "check " 3
I want the output string = "check check check"
我尝试了一个循环,但似乎无法使其正常工作.
I have tried with a loop, but couldn't seem to make it work.
有人吗?
推荐答案
实际上,该功能已经在字符串模块:
Actually the function is already in String module:
let multiply text times = String.replicate times text
要编写自己的函数,一种有效的方法是使用StringBuilder
:
To write your own function, an efficient way is using 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()
如果要删除示例中的结尾空格,可以使用String
类中的Trim()
成员来实现.
If you want to remove trailing whitespaces as in your example, you can use Trim()
member in String
class to do so.
这篇关于在F#中乘以字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!