5

I need to find the index of an item in an array of strings where that item's value matches a certain pattern.

Example array & values:

string[] stringArray = { "roleName","UserID=000000","OtherID=11111" }

I need to get the index of the item whose value begins with "UserID=". I know I could iterate through the array and match each value to a regex, but that just sounds slow and messy. I was thinking of doing something like this:

int indexIneed = Array.IndexOf(stringArray,"\bUserID=");

But I've never really had to mess with regular expressions before, so I fumbling around like a toddler. Is there I way I can accomplish what I'm tring to do in O(n) or am I going to have to resort to iteration?

3
  • 2
    What's wrong with the simple iteration? Why do you consider it "slow and messy"? It is O(n) in fact, if you do not take into account the regex matching cost. Commented Feb 3, 2015 at 20:24
  • IndexOf Iterates the array and is O(n). Commented Feb 3, 2015 at 20:25
  • @DixonD and Magnus You're both absolutely right. For some reason I was thinking it would be O(n<sup>2</sup>). Deadlines have me jumping to conclusions :) Commented Feb 3, 2015 at 20:32

1 Answer 1

7

FindIndex will give you what you want:

int indexIneed = Array.FindIndex(stringArray,s => s.StartsWith("UserID="));
Sign up to request clarification or add additional context in comments.

3 Comments

completely forgot about that. +1 :)
anyway, it is the same iteration, just one-liner. the same can be done with LINQ also
@DixonD not without creating unnecessary objects

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.