Search code examples
c#charindexof

How do you get IndexOf of a string with multiple possible chars?


I need a function which can get the first index of one of multiple possible chars. I don't want to use regex because of the bad performance. I tried getting the min of two IndexOf(s) but it doesn't work when it is contained in one string and not the other because -1 is smaller than both indexes.

public static int IndexOf (this string s, char a, char b) => 
    Math.Min(s.IndexOf(a), s.IndexOf(b));

Solution

  • I suggest a bit more complex, but I hope more convenient solution:

    // 1. Let's return not only index, but the char found as well
    // 2. Let's accept arbitrary number of characters
    // 3. Let's not interfere with existing IndexOf, IndexOfAny methods : IndexOfAnyChar
    public static (int index, char value) IndexOfAnyChar(this string s, params char[] toFind) {
      //DONE: input parameters validation
      if (null == s)
        return (-1, default(char)); // or throw ArgumentNullException(nameof(s))
      else if (null == toFind || toFind.Length <= 0)
        return (-1, default(char)); // or throw ArgumentNullException(nameof(toFind))
    
      int bestIndex = -1;
      char bestChar = default(char);
    
      foreach (char c in toFind) {
        // for the long strings let's provide count for efficency
        int index = s.IndexOf(c, 0, bestIndex < 0 ? s.Length : bestIndex);
    
        if (index >= 0) {
          bestIndex = index;
          bestChar = c;
        }
      }
    
      return (bestIndex, bestChar);
    }
    

    Demo:

    var result = "abcde".IndexOfAnyChar('e', 'z', 'd');
    
    // to get index only:
    // int index = "abcde".IndexOfAnyChar('e', 'z', 'd').index; 
    
    Console.Write(result);
    

    Outcome:

    (3, d)