如何在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循环中,我们将字符串“!”追加指定的次数。
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP