Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

วิธีค้นหาและแทนที่คำใน String ใน C#

กำหนดสตริงต้นฉบับ:

string str = "Demo text!";

ใช้ Replace():

string res = str.Replace("Demo ", "New ");

ตัวอย่าง

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

ผลลัพธ์

Demo text!
After replacing...
New text!