HasanG
HasanG

Reputation: 13161

Is there a built-in function to repeat a string or char in .NET?

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

Upvotes: 56

Views: 48651

Answers (5)

Chris Raisin
Chris Raisin

Reputation: 442

The best solution is the built in string function:

 Strings.StrDup(2, "a")

Upvotes: 9

Eli Dagan
Eli Dagan

Reputation: 848

new String('*', 5)

See Rosetta Code.

Upvotes: 5

Schiavini
Schiavini

Reputation: 2939

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

Upvotes: 34

Carter Medlin
Carter Medlin

Reputation: 12475

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

returns

"abab"

Upvotes: 62

Kirk Woll
Kirk Woll

Reputation: 77556

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

Returns

"abab"

And

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

Returns

"aa"

Upvotes: 65

Related Questions