We all work with string values in our daily programming life. Sometimes we might require a string variable to be initialized with strings of a repeated character.
Now let us come to the point.
.NET Framework String class already have a parameterized constructor to do the same.
String Constructor (Char, Int32)
C# Syntax:
public String( char c, int count )
MSDN: “Initializes a new instance of the String class to the value indicated by a specified Unicode character repeated a specified number of times.”
See the sample usage given below,
class Program { static void Main(string[] args) { int size = 10; string sample = new String('-', size); Console.WriteLine(sample); Console.ReadKey(); //Outputs : ---------- } }
This is the most straightforward and efficient way to initialize a string variable with strings of repeated characters.
Advertisements
Do not attempt to construct a string via this constructor in QuickWatch or Watch in Visual Studio until its Microsoft Connect issue is resolved:
https://connect.microsoft.com/VisualStudio/feedback/details/850420/quickwatch-argumentexception-on-valid-c-string-constructor-with-arguments