如何在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