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?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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

Returns

"abab"

And

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

Returns

"aa"

Method 2

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

returns

“abab”

Method 3

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

Method 4

new String('*', 5)

See Rosetta Code.

Method 5

The best solution is the built in string function:

 Strings.StrDup(2, "a")


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x