在C#中,字符串的替換操作可以通過多種方式實現。下面列舉了幾種常用的方法:
string originalString = "Hello, World!";
string newString = originalString.Replace("Hello", "Hi");
Console.WriteLine(newString); // 輸出:Hi, World!
using System.Text.RegularExpressions;
string originalString = "Hello, World!";
string newString = Regex.Replace(originalString, "Hello", "Hi");
Console.WriteLine(newString); // 輸出:Hi, World!
using System.Text;
string originalString = "Hello, World!";
StringBuilder sb = new StringBuilder(originalString);
sb.Replace("Hello", "Hi");
string newString = sb.ToString();
Console.WriteLine(newString); // 輸出:Hi, World!
string originalString = "Hello, {0}!";
string name = "Alice";
string newString = string.Format(originalString, "Hi");
Console.WriteLine(newString); // 輸出:Hi, Alice!
這些方法可以根據具體情況選擇使用,以實現字符串的替換操作。