Repeat
Repeat a string N times
Source
using System.Text;
namespace MyExtensions
{
public static class StringExtensions
{
public static string Repeat(this string input, int count)
{
if (input == null)
{
return null;
}
var sb = new StringBuilder();
for (var repeat = 0; repeat < count; repeat++)
{
sb.Append(input);
}
return sb.ToString();
}
}
}
Example
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using MyExtensions;
namespace StringExtensionsTests
{
[TestClass]
public class StringExtensionsTests
{
[TestMethod]
public void RepeatBlank10()
{
var repeat10 = "".Repeat(10);
Assert.AreEqual(0, repeat10.Length);
}
[TestMethod]
public void RepeatNull10()
{
string nullString = null;
// ReSharper disable once ExpressionIsAlwaysNull
var repeat10 = nullString.Repeat(10);
Assert.IsNull(repeat10);
}
[TestMethod]
public void RepeatSingle0()
{
var repeat10 = "x".Repeat(0);
Assert.AreEqual(0, repeat10.Length);
}
[TestMethod]
public void RepeatSingle10()
{
var repeat10 = "x".Repeat(10);
Assert.AreEqual(10, repeat10.Length);
}
[TestMethod]
public void RepeatMulti10()
{
var repeat10 = "xxx".Repeat(10);
Assert.AreEqual(30, repeat10.Length);
}
}
}