【发布时间】:2019-09-30 04:14:41
【问题描述】:
我创建了一个函数,通过使用 .Replace 方法删除各种字符来“过滤”字符串,我还使用 Substring 方法删除了以 '(' 开头的字符串末尾的任何内容。
这一切都很好,但是我想知道是否有优化的更好的方法来做到这一点,因为效率对我来说很重要。
public static string filterHorseName(string horseName)
{
horseName = horseName
.Replace(" ", "")
.Replace("`", "")
.Replace("-", "")
.Replace("'", "")
.Replace("´", "")
.Replace("’", "")
.ToLower();
int index = horseName.IndexOf("(");
if (index > 0)
{
horseName = horseName.Substring(0, index);
}
return horseName;
}
谢谢。
【问题讨论】:
-
当您问这些类型的问题时,最好输入您的输入和预期输出
-
效率对每个人都很重要。您是否对这段代码进行了基准测试?它被证明是一个瓶颈吗?不要只是重命名你的马,race them。无论如何,你在这里创建了很多垃圾字符串。每个
Replace()和Substring()返回一个新字符串,使旧字符串符合垃圾回收条件。 -
这里有很多不同的方法来做到这一点。 stackoverflow.com/questions/7265315/…。一个简单的github.com/dotnet/BenchmarkDotNet 与他们比赛?
-
因为替换字符是空的。你可以简单地用 Where 子句过滤它们。
-
考虑使用 StringBuilder 创建字符串。字符串是不可变对象,每次执行 Replace() 时都会创建一个新实例。
标签: c# string replace filter indexof