54

Is there a function in C# that returns x times of a given char or string? Or must I code it myself?

Pang
  • 9,564
  • 146
  • 81
  • 122
HasanG
  • 12,734
  • 29
  • 100
  • 154
  • 1
    this is not an exact duplicate: this is a way to do it. Dim line As String = New [String]("-"c, 100) – KevinDeus Apr 28 '12 at 00:49
  • 2
    Well, better late than never. I voted for re-opening this as it is **not** a duplicate of linked possible duplicate. [Best way to repeat a character in C#](http://stackoverflow.com/questions/411752/best-way-to-repeat-a-character-in-c-sharp) does **not** cover repeating strings but only characters! – Nope Dec 13 '12 at 13:09
  • possible duplicate of [Can I "multiply" a string (in C#)?](http://stackoverflow.com/questions/532892/can-i-multiply-a-string-in-c) – Deanna Mar 05 '14 at 08:50
  • 6
    possible duplicate of [Is there an easy way to return a string repeated X number of times?](http://stackoverflow.com/questions/3754582/is-there-an-easy-way-to-return-a-string-repeated-x-number-of-times) – Pekka Apr 04 '14 at 09:59

5 Answers5

66
string.Join("", Enumerable.Repeat("ab", 2));

Returns

"abab"

And

string.Join("", Enumerable.Repeat('a', 2))

Returns

"aa"
Kirk Woll
  • 76,112
  • 22
  • 180
  • 195
  • 3
    slightly more correct answers below -- use the native 'join' for characters [(1)](http://stackoverflow.com/a/19248082/1037948), or `string.Concat` for strings [(2)](http://stackoverflow.com/a/15390834/1037948) – drzaus Jan 14 '14 at 17:54
  • If code already uses Linq, use `string.Join("", Enumerable.Repeat("ab", 2).ToArray());` – Sanjay Apr 04 '14 at 12:10
  • For chars as mentioned new string(char ch, int count) is better. An improvement of this could be to use Concat. – Corniel Nobel Sep 21 '17 at 11:35
60
string.Concat(Enumerable.Repeat("ab", 2));

returns

"abab"

Carter Medlin
  • 11,857
  • 5
  • 62
  • 68
31

For strings you should indeed use Kirk's solution:

string.Join("", Enumerable.Repeat("ab", 2));

However for chars you might as well use the built-in (more efficient) string constructor:

new string('a', 2); // returns aa
Schiavini
  • 2,869
  • 2
  • 23
  • 49
  • Deserved 1 point for Mentioning the proper way to repeat Character. You can see http://stackoverflow.com/questions/411752/best-way-to-repeat-a-character-in-c-sharp too. Good Luck. – QMaster Dec 09 '14 at 15:28
4
new String('*', 5)

See Rosetta Code.

bluish
  • 26,356
  • 27
  • 122
  • 180
Eli Dagan
  • 808
  • 8
  • 14
4

The best solution is the built in string function:

 Strings.StrDup(2, "a")
Chris Raisin
  • 384
  • 3
  • 7