Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

char

indexof

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));
like image 293
trinalbadger587 Avatar asked Oct 20 '25 09:10

trinalbadger587


1 Answers

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)
like image 70
Dmitry Bychenko Avatar answered Oct 23 '25 00:10

Dmitry Bychenko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!