Surendra Sharma

Surendra Sharma

Search This Blog

Saturday, March 28, 2015

How to repeat particular string or char into certain number of times

I was writing a program for showing a tree structure in textbox. I was trying to concatenate tabs and spaces in string. Soon I realize that it’s a very tedious way to achieve the result. I thought that .NET is the Ocean and there must be some way to repeat the particular string or character certain number of times. For example if I have character ‘0’ and I want to display it 5 times on screen. 

How to do it?

FOR and FOR EACH Loops are common, but I need some more smart way do it.
Here are some ways that I found

int count = 5;
string str = "PEACE ";
char c = '0';

Console.WriteLine(String.Empty.PadLeft(count, c));     //Output- 00000

string result = new String(c, count);
Console.WriteLine(result); //Output- 00000

Console.WriteLine(new StringBuilder().Insert(0, str, count).ToString());   //Output- PEACE PEACE PEACE PEACE PEACE

First two only repeat characters while last way is to repeat string. Hope this help someone.

Please leave your comments or share this code if it’s useful for you.

No comments:

Post a Comment