C# Tips and Tricks #19 – Repeat a character N times

Here’s a quick one. Its rather a simple tip demonstrating how to repeat a character N times in C#.

How to repeat a character N times in C# ?

Imagine that you want to repeat a character “X” , 5 times. One of the simplest way to do it is using the constructor of the string class and passing the character(X) and 5 as its parameters as shown below.

using System;
namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            string tabs = new String('X', 5);
            Console.WriteLine(tabs);

            Console.ReadLine();
        }
    }
}
    

This will display the character X , 5 times as shown below.

image
Pin It

Leave a Reply

Your email address will not be published. Required fields are marked *