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

Thay thế ký tự bằng dấu sao trong chuỗi C#

Dùng string.Replace(char oldChar, char newChar) để thay thế tất cả lần xuất hiện của một ký tự.

Ví dụ minh họa

using System;

class Program
{
    static void Main()
    {
        string str = "dem* text";
        Console.WriteLine($"Chuỗi gốc: {str}");
        
        // Thay thế '*' bằng 'o'
        string result = str.Replace('*', 'o');
        Console.WriteLine($"Sau thay thế: {result}");
        
        // Thay thế nhiều ký tự (chuỗi)
        string str2 = "H*ll* W*rld";
        string result2 = str2.Replace("*", "o");
        Console.WriteLine($"\nChuỗi gốc: {str2}");
        Console.WriteLine($"Sau thay thế: {result2}");
        
        // Chuỗi bất biến - Replace trả về chuỗi mới
        Console.WriteLine($"\nChuỗi gốc không đổi: {str}");
    }
}

Kết quả đầu ra

Chuỗi gốc: dem* text
Sau thay thế: demo text

Chuỗi gốc: H*ll* W*rld
Sau thay thế: Hello World

Chuỗi gốc không đổi: dem* text

Lưu ý: string trong C# bất biến (immutable). Replace trả về instance mới, không sửa đổi chuỗi gốc. Gán kết quả vào biến mới.