Đầu tiên, đặt chuỗi được thay thế.
string str = "Demo text!";
Bây giờ, hãy sử dụng phương thức Replace () để thay thế chuỗi trên.
string res = str.Replace("Demo ", "New "); Sau đây là mã hoàn chỉnh để thay thế một từ trong một chuỗi.
Ví dụ
using System;
public class Demo {
public static void Main() {
string str = "Demo text!";
Console.WriteLine(str);
string res = str.Replace("Demo ", "New ");
Console.WriteLine("After replacing...");
Console.WriteLine(res);
}
} Đầu ra
Demo text! After replacing... New text!