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

更新於: 22-6 月-2020

4K+ 次檢視

開啟您的職業生涯

透過完成課程獲得認證

開始
廣告
© . All rights reserved.