在VBScript中是否有内置函数可以重复一个字符串N次?

10

VBScript中有一个函数String(number,character),它返回一个包含指定长度重复字符的字符串。例如:

String(5, "A")     ' output: "AAAAA"

有没有函数可以重复一个字符串?例如:
RepeatString(5, "Ab")     ' output "AbAbAbAbAb"

你是在什么上下文中使用VBScript?虽然没有内置的功能,但你可以声明自己的函数来完成这个任务。 - apc
3
https://www.rosettacode.org/wiki/Repeat_a_string#VBScript - Wiktor Stribiżew
@WiktorStribiżew,我认为你应该提取涉及VBScript的代码部分,并将其作为答案发布(附带参考链接)。 - Victor Moraes
@VictorMoraes:我本想回答,但是Alex回答得更快。我认为他的回答已经足够了。我一开始是在寻找重复问题,并没有专注于回答。 - Wiktor Stribiżew
@WiktorStribiżew你的链接提供了两种方法,而Alex只有一种,但是也许这已经足够了。 - Victor Moraes
6个回答

43

不,没有内置的功能。相反:

n      = 5
str    = "Ab"
result = replace(space(n), " ", str)

巧妙!Replace(Space(3)," ","ha") - dakab

3

为了代码简洁,被接受的答案不错。但是下面的函数实际上快了10倍。而且它比RepeatString()快两倍。它使用了Mid的一个鲜为人知的功能,它可以一次性用一个重复模式填充字符串缓冲区的剩余部分...

Function Repeat$(ByVal n&, s$)
    Dim r&
    r = Len(s)
    If n < 1 Then Exit Function
    If r = 0 Then Exit Function
    If r = 1 Then Repeat = String$(n, s): Exit Function
    Repeat = Space$(n * r)
    Mid$(Repeat, 1) = s: If n > 1 Then Mid$(Repeat, r + 1) = Repeat
End Function

我已经有一段时间没有做VBA了,所以也没有跟上语法的更新,所以这段代码相当晦涩。 - go2null
没有新的语法。实际上,这个函数可以在1980年代的BASIC中使用。 - Excel Hero
我之前没有见过 String$(n, s) 这个函数。它是做什么用的?我以为它和 Space$(n * r) 的功能类似,但是在微软的 VBA 文档中找不到它的介绍。 - chaotic3quilibrium
https://learn.microsoft.com/en-us/office/vba/language/reference/user-interface-help/string-function - Excel Hero
VBScript 没有 mid$ 语句。 - Antoni Gual Via

2

对于一般简单的解决方案

Function RepeatString( number, text )
    Redim buffer(number)
    RepeatString = Join( buffer, text )
End Function

但如果文本很短但重复次数很多,这将是一个更快的解决方案。

Function RepeatString( ByVal number, ByVal text )
    RepeatString=""
    While (number > 0)
        If number And 1 Then 
            RepeatString = RepeatString & text
        End If 
        number = number \ 2 
        If number > 0 Then
            text = text & text 
        End If 
    Wend
End Function

0

这里有另一种使用内置的Excel公式REPT()来完成此操作的方法。

Function RepeatMyStringTimes()
    Const myString As String = "Some String"
    Const Times As Byte = 7
    Debug.Print Excel.WorksheetFunction.Rept("S", Times)
End Function

-1
我们可以创建一个简单的自定义函数,就像这样:
Function RepeatString(Byval AString As String, byval Times As Long)
    If AString = vbNullString Or Times < 0 Then RepeatString = CVErr(xlErrNA): Exit Function
    Dim i As Long
    Dim result As String
    For i = 1 To Times
        result = result & AString
    Next
    RepeatString = result
End Function

或者使用String函数返回指定长度的重复字符字符串。
Dim MyString
MyString = String(5, "*")    ' Returns "*****".
MyString = String(5, 42)    ' Returns "*****".
MyString = String(10, "ABC")    ' Returns "AAAAAAAAAA".

1
你不应该未经归属地复制/粘贴互联网上的内容。那是剽窃行为。 - Geert Bellekens

-1

顺便说一下,我需要将一个10个字符的字符串重复超过2500万次,函数Repeat $(ByVal n&,s $)只需半秒钟即可完成,它救了我的一天!:)


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接