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:
[code language=”csharp”]
public String(
char c,
int count
)
[/code]
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,
[code language=”csharp” highlight=”7″]
class Program
{
static void Main(string[] args)
{
int size = 10;
string sample = new String(‘-‘, size);
Console.WriteLine(sample);
Console.ReadKey();
//Outputs : ———-
}
}[/code]
This is the most straightforward and efficient way to initialize a string variable with strings of repeated characters.