如何在C#中返回重复N次的字符串?

使用字符串实例string repeatString =新字符串(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 repeatString = 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循环中,我们附加字符串“!”。指定次数。