devxlogo

Replicate a string of any length

The String$ function can replicate only 1-char strings, so it seems that you need a loop to duplicate strings that contain 2 or more characters. However, this is a one-liner that does the trick:

Function ReplicateString(Source As String, Times As Long) As String    ' build a string of spaces whose length is equal to the number of    ' repetitions, then replace each space with the string to be repeated    ReplicateString = Replace$(Space$(Times), " ", Source)End Function

Note, however, that – depending on the length of the string and the number of repetitions – this approach might be slower than an optimized code based on a loop.

Charlie has over a decade of experience in website administration and technology management. As the site admin, he oversees all technical aspects of running a high-traffic online platform, ensuring optimal performance, security, and user experience.

See also  Five Early Architecture Decisions That Quietly Get Expensive

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.