
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Return a String Repeated n Number of Times in C#
Use string instance string repeatedString = new string(charToRepeat, 5) to repeat the character "!" with specified number of times.
Use string.Concat(Enumerable.Repeat(charToRepeat, 5)) to repeat the character "!" with specified number of times.
Use StringBuilder builder = new StringBuilder(stringToRepeat.Length * 5); to repeat the character "!" with specified number of times.
Using string instance
Example
using System; namespace DemoApplication{ public class Program{ static void Main(string[] args){ string myString = "Hi"; Console.WriteLine($"String: {myString}"); char charToRepeat = '!'; Console.WriteLine($"Character to repeat: {charToRepeat}"); string repeatedString = new string(charToRepeat, 5); Console.WriteLine($"Repeated Number: {myString}{repeatedString}"); Console.ReadLine(); } } }
Output
String: Hi Character to repeat: ! Repeated String: Hi!!!!!
In the above example using string instance string repeatedString = new string(charToRepeat, 5) we are specifying the character "!" should repeat the specified number of times.
Using string.Concat and Enumberable.Repeat −
Example
using System; using System.Linq; namespace DemoApplication{ public class Program{ static void Main(string[] args){ string myString = "Hi"; Console.WriteLine($"String: {myString}"); char charToRepeat = '!'; Console.WriteLine($"Character to repeat: {charToRepeat}"); var repeatedString = string.Concat(Enumerable.Repeat(charToRepeat, 5)); Console.WriteLine($"Repeated String: {myString}{repeatedString}"); Console.ReadLine(); } } }
Output
String: Hi Character to repeat: ! Repeated String: Hi!!!!!
In the above example using string instance string.Concat(Enumerable.Repeat(charToRepeat, 5)) we are repeating the character "!" with specified number of times.
Using StringBuilder
Example
using System; using System.Text; namespace DemoApplication{ public class Program{ static void Main(string[] args){ string myString = "Hi"; Console.WriteLine($"String: {myString}"); string stringToRepeat = "!"; Console.WriteLine($"String to repeat: {stringToRepeat}"); StringBuilder builder = new StringBuilder(stringToRepeat.Length * 5); for (int i = 0; i < 5; i++){ builder.Append(stringToRepeat); } string repeatedString = builder.ToString(); Console.WriteLine($"Repeated String: {myString}{repeatedString}"); Console.ReadLine(); } } }
Output
String: Hi Character to repeat: ! Repeated String: Hi!!!!!
In the above example using string builder we are getting the length of the string to be repeated. Then in the for loop we are appending the string "!" with specified number of times.