VBScript中有一个函数String(number,character)
,它返回一个包含指定长度重复字符的字符串。例如:
String(5, "A") ' output: "AAAAA"
有没有函数可以重复一个字符串?例如:
RepeatString(5, "Ab") ' output "AbAbAbAbAb"
VBScript中有一个函数String(number,character)
,它返回一个包含指定长度重复字符的字符串。例如:
String(5, "A") ' output: "AAAAA"
RepeatString(5, "Ab") ' output "AbAbAbAbAb"
不,没有内置的功能。相反:
n = 5
str = "Ab"
result = replace(space(n), " ", str)
Replace(Space(3)," ","ha")
- dakab为了代码简洁,被接受的答案不错。但是下面的函数实际上快了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
String$(n, s)
这个函数。它是做什么用的?我以为它和 Space$(n * r)
的功能类似,但是在微软的 VBA 文档中找不到它的介绍。 - chaotic3quilibrium对于一般简单的解决方案
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
这里有另一种使用内置的Excel公式REPT()来完成此操作的方法。
Function RepeatMyStringTimes()
Const myString As String = "Some String"
Const Times As Byte = 7
Debug.Print Excel.WorksheetFunction.Rept("S", Times)
End Function
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
Dim MyString
MyString = String(5, "*") ' Returns "*****".
MyString = String(5, 42) ' Returns "*****".
MyString = String(10, "ABC") ' Returns "AAAAAAAAAA".
顺便说一下,我需要将一个10个字符的字符串重复超过2500万次,函数Repeat $(ByVal n&,s $)只需半秒钟即可完成,它救了我的一天!:)