1

I have created a function to 'filter' a string by removing various characters using the .Replace method, I am also removing anything at the end of the string that starts with '(' using the Substring method.

This all works fine, however I am wondering if there is a optimised better way of doing this as efficiency is important for me.

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;
}

Thank you.

5
  • 1
    When you ask these types of questions its optimal to put in your inputs and intended outputs Commented May 13, 2019 at 8:23
  • Efficiency is important for everyone. Did you benchmark this code? Is it proven to be a bottleneck? Don't just rename your horses, race them. Anyway, you're creating a lot of garbage strings here. Each Replace() and Substring() returns a new string, leaving the old one eligible for garbage collection. Commented May 13, 2019 at 8:24
  • Here is a lot of different way to do this. stackoverflow.com/questions/7265315/…. a simple github.com/dotnet/BenchmarkDotNet to race them? Commented May 13, 2019 at 8:24
  • And as the replacment char is Nothing. wou can simply filter them with a Where clause. Commented May 13, 2019 at 8:28
  • Consider using a StringBuilder to create the string. Strings are immutable objects, each time you do a Replace() you are creating a new instance. Commented May 13, 2019 at 8:29

1 Answer 1

4

I suggest building the final string with a help of StringBuilder:

    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(); 
    } 
Sign up to request clarification or add additional context in comments.

1 Comment

This is quite simply the answer.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.