如何在 C# 中返回重复 N 次的字符串?
csharpserver side programmingprogramming更新于 2025/6/26 9:37:17
使用字符串实例 string repeatedString = new string(charToRepeat, 5) 重复指定次数的字符"!"。
使用 string.Concat(Enumerable.Repeat(charToRepeat, 5)) 重复指定次数的字符"!"。
使用 StringBuilder builder = new StringBuilder(stringToRepeat.Length * 5); 重复指定次数的字符"!"。
使用字符串实例
示例
using System; namespace DemoApplication{ public class Program{ static void Main(string[] args){ string myString = "Hi"; Console.WriteLine($"String: {myString}"); char charToRepeat = '!'; Console.WriteLine($"Character to repeat: {charToRepeat}"); string repeatedString = new string(charToRepeat, 5); Console.WriteLine($"Repeated Number: {myString}{repeatedString}"); Console.ReadLine(); } } }
输出
String: Hi Character to repeat: ! Repeated String: Hi!!!!!
在上面的例子中,我们使用string 实例 string repeatedString = new string(charToRepeat, 5)来指定字符"!"应重复指定的次数。
使用 string.Concat 和 Enumberable.Repeat −
示例
using System; using System.Linq; namespace DemoApplication{ public class Program{ static void Main(string[] args){ string myString = "Hi"; Console.WriteLine($"String: {myString}"); char charToRepeat = '!'; Console.WriteLine($"Character to repeat: {charToRepeat}"); var repeatedString = string.Concat(Enumerable.Repeat(charToRepeat, 5)); Console.WriteLine($"Repeated String: {myString}{repeatedString}"); Console.ReadLine(); } } }
输出
String: Hi Character to repeat: ! Repeated String: Hi!!!!!
在上面的例子中,我们使用字符串实例 string.Concat(Enumerable.Repeat(charToRepeat, 5)) 来重复字符"!"指定的次数。
使用 StringBuilder
示例
using System; using System.Text; namespace DemoApplication{ public class Program{ static void Main(string[] args){ string myString = "Hi"; Console.WriteLine($"String: {myString}"); string stringToRepeat = "!"; Console.WriteLine($"String to repeat: {stringToRepeat}"); StringBuilder builder = new StringBuilder(stringToRepeat.Length * 5); for (int i = 0; i < 5; i++){ builder.Append(stringToRepeat); } string repeatedString = builder.ToString(); Console.WriteLine($"Repeated String: {myString}{repeatedString}"); Console.ReadLine(); } } }
输出
String: Hi Character to repeat: ! Repeated String: Hi!!!!!
在上面的例子中,我们使用字符串构建器获取了需要重复的字符串的长度。然后在 for 循环中,我们以指定的次数附加字符串"!"。