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


使用字符串实例 **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 repeatedString = new string(charToRepeat, 5)**,我们指定字符“!”应该重复指定的次数。

使用string.Concat和Enumerable.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!!!!!

在上例中,使用StringBuilder,我们获取要重复的字符串的长度。然后在for循环中,我们将字符串“!”追加指定的次数。

更新于:2020年9月24日

4K+ 次查看

开启你的职业生涯

通过完成课程获得认证

开始学习
广告
© . All rights reserved.