简体   繁体   中英

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?

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

Returns

"abab"

And

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

Returns

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

returns

"abab"

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
new String('*', 5)

请参阅罗塞塔代码

最好的解决方案是内置的字符串函数:

 Strings.StrDup(2, "a")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM