Create a String Consisting of a Repeated Character

Problem

You need to quickly create a string that consists of a single character repeated multiple times (for example, "------------").

Solution

Use the overloaded String constructor that accepts a single character and a repetition number.

Discussion

The following code creates a string made up of 100 dash characters. Note that in order to use the nondefault String constructor, you must use the New keyword when you declare the string.

Dim Dashes As New String("-"c, 100)

When specifying the character to repeat, you can append the letter c after the string to signal that the quoted text represents a Char, as required by this constructor, not a String. This is required if you have Option Strict enabled, which ...

Get Microsoft® Visual Basic® .NET Programmer's Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.