C# 字符串 - Replace() 方法
C# 字符串 Replace() 方法用于将当前字符串中所有出现的指定 Unicode 字符或字符串替换为另一个指定的字符或字符串,从而返回一个新字符串。
需要注意的是,此方法可以通过传递不同的参数进行重载。在下面的示例中,我们可以使用重载的 Replace() 方法。
语法
以下是 C# 字符串 Replace(Char) 方法的语法 -
public string Replace (char oldChar, char newChar);
参数
此方法接受以下参数 -
- oldChar/oldValue:可以是 Unicode 字符,也可以是要替换的字符串。
- newChar/newValue:可以是 Unicode 字符,也可以是用于替换所有 oldChar 或 newValue 的字符串。
返回值
此方法返回一个字符串,该字符串等于当前字符串,但所有旧值均已替换为 newValue。如果在当前实例中找不到 oldValue,则该方法返回未更改的当前实例。
示例 1:使用 Replace (string oldValue, string? newValue)
以下基本示例演示了如何使用 Replace 方法更正拼写错误 -
using System; using System.Globalization; class Program { public static void Main() { string errString = "This docment uses 3 other docments to docment the docmentation"; Console.WriteLine($"The original string is:{Environment.NewLine}{errString}"); // 更正"document"的拼写。 string correctString = errString.Replace("docment", "document"); Console.WriteLine($"After correcting the string, the result is:{Environment.NewLine}{correctString}"); } }
输出
以下是输出 -
The original string is: This docment uses 3 other docments to docment the docmentation After correcting the string, the result is: This document uses 3 other documents to document the documentation
示例 2:使用 Replace(char oldChar, char newChar)
让我们看一下 Replace() 方法的另一个示例。我们通过用逗号替换一系列数字之间的空格来创建一个逗号分隔的值列表 -
using System; using System.Globalization; class Program { public static void Main() { string str = "1 2 3 4 5 6 7 8 9"; Console.WriteLine("Original string: " + $"\"{str}\""); // 使用 Replace() 方法 string csv_string = str.Replace(' ', ','); Console.WriteLine("CSV string: " + $"\"{csv_string}\""); } }
输出
以下是输出 -
Original string: "1 2 3 4 5 6 7 8 9" CSV string: "1,2,3,4,5,6,7,8,9"
示例 3:替换重复出现的字符
在本例中,我们使用 Replace() 方法将重复出现的旧字符替换为新字符 -
using System; class Program { public static void Main() { string text = "mississippi"; string result = text.Replace('i', 'o'); Console.WriteLine(result); } }
输出
以下是输出 -
mossossoppo
示例 4:替换和链式操作
在本例中,我们使用 Replace() 方法替换字符串中的多个子字符串。它会创建一个新的字符串,其中特定的子字符串会被其他子字符串替换 -
using System; class Program { public static void Main() { string text = "hello world"; string result = text.Replace("hello", "hi").Replace("world", "tutorialspoint"); Console.WriteLine(result); } }
输出
以下是输出 -
hi tutorialspoint