【问题标题】:Filtering string with Replace & Substring in C# Optimisation [duplicate]在 C# 优化中使用替换和子字符串过滤字符串 [重复]
【发布时间】: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


【解决方案1】:

我建议在StringBuilder 的帮助下构建最终的string

    private static HashSet<char> charsToRemove = new HashSet<char>() {
      ' ', '`', '-', '\'', '´', '’'
    };

    public static string filterHorseName(string horseName) {
      if (string.IsNullOrEmpty(horseName)) 
        return horseName;

      StringBuilder sb = new StringBuilder(horseName.Length);  

      foreach (char c in horseName) {
        if (charsToRemove.Contains(c)) 
          continue;
        else if (c == '(') 
          break;

        sb.Append(char.ToLower(c));
      }

      return sb.ToString(); 
    } 

【讨论】:

  • 答案很简单。
猜你喜欢
  • 2014-11-05
  • 2022-01-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-10-08
  • 1970-01-01
  • 2013-05-18
相关资源
最近更新 更多