System.String.Replace 方法 (String, String)

方法描述

返回一个新字符串,其中当前实例中出现的所有指定字符串都替换为另一个指定的字符串。

语法定义(C# System.String.Replace 方法 (String, String) 的用法)

public string Replace(
	string oldValue,
	string newValue
)

参数/返回值

参数值/返回值 参数类型/返回类型 参数描述/返回描述
oldValue System-String 要被替换的字符串。
newValue System-String 要替换出现的所有 oldValue 的字符串。
返回值 System.String 与当前字符串等效的一个字符串,但其中 oldValue 的所有实例都替换为 newValue。

提示和注释

如果 newValue 为 null,则移除 oldValue 的所有匹配项。

注意

此方法不修改当前实例的值。 而是返回一个新字符串,其中 oldValue 的所有匹配项均被替换为 newValue。

此方法执行序号(区分大小写但不区分区域性)搜索以查找 oldValue。

System.String.Replace 方法 (String, String)例子

下面的示例演示如何使用 Replace 方法来更正拼写错误。

using System;

public class ReplaceTest {
    public static void Main() {

        string errString = "This docment uses 3 other docments to docment the docmentation";

        Console.WriteLine("The original string is:{0}'{1}'{0}", Environment.NewLine, errString);

        // Correct the spelling of "document".

        string correctString = errString.Replace("docment", "document");

        Console.WriteLine("After correcting the string, the result is:{0}'{1}'",
                Environment.NewLine, correctString);
    }
}
//
// This code example produces the following output:
//
// 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'
//

异常

异常 异常描述
ArgumentNullException oldValue 为 null。
ArgumentException oldValue 是空字符串 ("")。

命名空间

namespace: System

程序集: mscorlib(在 mscorlib.dll 中)

版本信息

.NET Framework 受以下版本支持:4、3.5、3.0、2.0、1.1、1.0 .NET Framework Client Profile 受以下版本支持:4、3.5 SP1 受以下版本支持:

适用平台

Windows 7, Windows Vista SP1 或更高版本, Windows XP SP3, Windows XP SP2 x64 Edition, Windows Server 2008(不支持服务器核心), Windows Server 2008 R2(支持 SP1 或更高版本的服务器核心), Windows Server 2003 SP2 .NET Framework 并不是对每个平台的所有版本都提供支持。有关支持的版本的列表,请参见.NET Framework 系统要求。