gpt4 book ai didi

c# - 我应该在 string.Replace() 之前使用 string.Contains() 吗?

转载 作者:太空狗 更新时间:2023-10-29 20:56:18 25 4
gpt4 key购买 nike

在进行字符串替换之前是否不需要这个 if 语句?

 if (myString.Contains(oldValue))
{
myString = myString.Replace(oldValue, newValue);
}

最佳答案

所有详细信息都在 String.Replace 的文档中:

Return Value:
A string that is equivalent to the current string except that all instances of oldValue are replaced with newValue. If oldValue is not found in the current instance, the method returns the current instance unchanged.

不需要 if 语句。

if 语句甚至不是性能优化,因为如果 oldValue 未找到,String.Replace 会返回相同的对象实例。我已经使用以下代码对此进行了验证:

namespace StringReplaceTest
{
class Program
{
static void Main(string[] args)
{
string s = "Test";
string s2 = s.Replace("Foo", "Bar");
string s3 = s.Replace("es", "tt");
}
}
}

使用方便的制作对象 ID 功能(右键单击 LocalsAutoWatch 窗口;有关更多详细信息,请参阅 Common Expression Evaluator Features)产生以下输出:

s  | "Test" {$1}
s2 | "Test" {$1}
s3 | "Tttt" {$2}

关于c# - 我应该在 string.Replace() 之前使用 string.Contains() 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34404042/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com