Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C#

Cách trả về string lặp lại N lần trong C#

Dùng string instance string repeatedString = new string(charToRepeat, 5) để lặp lại ký tự "!" số lần chỉ định.

Dùng string.Concat(Enumerable.Repeat(charToRepeat, 5)) để lặp lại ký tự "!" số lần chỉ định.

Dùng StringBuilder builder = new StringBuilder(stringToRepeat.Length * 5); để lặp lại ký tự "!" số lần chỉ định.

Dùng string instance

Ví dụ

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 String: {myString}{repeatedString}"); 
            Console.ReadLine(); 
        } 
    } 
}

Output

String: Hi
Character to repeat: !
Repeated String: Hi!!!!!

Trong ví dụ trên dùng string instance string repeatedString = new string(charToRepeat, 5) chỉ định ký tự "!" lặp lại số lần chỉ định.

Dùng string.Concat và Enumerable.Repeat

Ví dụ

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(); 
        } 
    } 
}

Output

String: Hi
Character to repeat: !
Repeated String: Hi!!!!!

Trong ví dụ trên dùng string.Concat(Enumerable.Repeat(charToRepeat, 5)) lặp lại ký tự "!" số lần chỉ định.

Dùng StringBuilder

Ví dụ

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(); 
        } 
    } 
}

Output

String: Hi
Character to repeat: !
Repeated String: Hi!!!!!

Trong ví dụ trên dùng StringBuilder lấy độ dài string cần lặp. Sau đó trong for loop append string "!" số lần chỉ định.

Mở rộng: Lặp chuỗi (string) không chỉ ký tự

1. String.Concat + Enumerable.Repeat (cho string)

string repeated = string.Concat(Enumerable.Repeat("Hi", 3)); // "HiHiHi"

2. StringBuilder (hiệu quả nhất cho string lớn/số lần nhiều)

public static string RepeatString(string s, int count) {
    if (string.IsNullOrEmpty(s) || count <= 0) return string.Empty;
    var builder = new StringBuilder(s.Length * count);
    for (int i = 0; i < count; i++) builder.Append(s);
    return builder.ToString();
}

3. string.Join (có separator)

string repeated = string.Join("-", Enumerable.Repeat("Hi", 3)); // "Hi-Hi-Hi"

4. C# 11+ raw string literals (không liên quan nhưng hữu ích)

// C# 11: new string('*', 10) vẫn hoạt động
// Hoặc pattern matching
string Repeat(char c, int n) => n switch {
    <= 0 => "",
    1 => c.ToString(),
    _ => new string(c, n)
};

So sánh Performance

Phương pháp Char String Ghi chú
new string(char, count) ✅ Nhanh nhất ❌ Không áp dụng Chỉ cho single char
StringBuilder ✅ Nhanh ✅ Nhanh nhất Best cho string, large count
string.Concat + Enumerable.Repeat ✅ OK ✅ OK Linq overhead nhẹ
string.Join ❌ Không trực tiếp ✅ OK Có separator
For loop + += ❌ Chậm ❌ Rất chậm Tạo nhiều string rác (immutable)