C# String Replace()

Replace() 方法通过将字符串中每个匹配的字符/子字符串替换为新的字符/子字符串来返回一个新的字符串。

示例

using System;  
namespace CsharpString {  
  class Test {
    public static void Main(string [] args) {

      string str = "Programming is fun";
    
// replaces "Programming" with "C#" string result = str.Replace("Programming", "C#");
Console.WriteLine(result); Console.ReadLine(); } } } // Output: C# is fun

Replace() 语法

字符串 Replace() 方法的语法是

Replace(string oldValue, string newValue)

这里,Replace()String 类的一个方法。


Replace() 参数

Replace() 方法接受以下参数

  • oldValue - 我们想要替换的子字符串
  • newValue - 将替换旧子字符串的新子字符串

Replace() 返回值

  • Replace() 方法通过将字符串中每个匹配的字符/子字符串替换为新的字符/子字符串来返回一个新的字符串。

示例 1:C# String Replace() 字符

using System;  
namespace CsharpString {  
  class Test {
    public static void Main(string [] args) {
 
      string str = "Bat";
      Console.WriteLine("Old value: " + str);
     
      string result;
 
// replaces 'B' with 'C'' result = str.Replace('B', 'C');
Console.WriteLine("New value: " + result); Console.ReadLine(); } } }

输出

Old value: Bat
New value: Cat

在上面的示例中,Replace() 方法将字符 'B' 替换为 'C'


示例 2:C# String Replace() 子字符串

using System;  
namespace CsharpString {  
  class Test {
    public static void Main(string [] args) {
 
      string str = "C# Programming";     
      string result;
 
// replaces "C#" with "Java" result = str.Replace("C#", "Java");
Console.WriteLine("New Value1: " + result);
// returns initial string result = str.Replace("Go", "C++");
Console.WriteLine("New Value2: " + result); Console.ReadLine(); } } }

输出

New Value1: Java Programming
New Value2: C# Programming
  • str.Replace("C#", "Java") - 将子字符串 "C#" 替换为字符串 "Java"
  • str.Replace("Go", "C++") - 返回初始字符串,因为没有 "Go" 子字符串

示例 3:Replace() 链式调用

using System;  
namespace CsharpString {  
  class Test {
    public static void Main(string [] args) {
 
      string str = "AAA";
      Console.WriteLine("Old Value: "+ str);
     
      string result;

// performs multiple replacement result = str.Replace("AAA", "BBB").Replace("BBB", "CCC");
Console.WriteLine("New Value: " + result); Console.ReadLine(); } } }

输出

Old Value: AAA
New Value: CCC

在上面的示例中,我们在初始字符串中执行了多个替换。

方法调用从左到右执行。所以,

  • 首先,"AAA" 将被替换为 "BBB"
  • 然后,"BBB" 将被替换为 "CCC"

因此,我们得到 "CCC" 作为输出。

注意Replace() 方法不会修改当前实例的值。相反,它通过替换旧值的新值出现来返回一个新的字符串。

你觉得这篇文章有帮助吗?

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战