如何在C#中返回重复N次的字符串?
使用字符串实例stringrepeatString=新字符串(charToRepeat,5)重复字符“!”指定次数。
使用string.Concat(Enumerable.Repeat(charToRepeat,5))重复字符“!”指定次数。
使用StringBuilderbuilder=newStringBuilder(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!!!!!
在上面的示例中,使用字符串实例stringrepeatString=newstring(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循环中,我们附加字符串“!”。指定次数。
热门推荐
1 训练狗狗工作
4 狗狗定点排便训练
5 狗狗训练吠叫
6 狗狗尿垫训练
7 狗狗训练座
8 狗狗训练攻略
9 狗狗训练记
10 做训练狗狗
11 狗狗训练词
12 狗狗谢谢怎么训练
13 狗狗训练如厕
14 狗狗太凶怎么训练
15 狗狗训练它
16 狗狗克制训练
17 训练基地狗狗
18 怎么样训练狗狗大小硬