So I have dealt with this problem before and thought there would be an accepted pattern to solve the problem, but I have yet to find anything. I tried searching around and I have tried tinkering around myself and neither resulted in any satisfactory answers so I am turning to SO
String str = "blah1blah2"
I want to know whether the char ‘1’ or ‘2’ occurs first (this is just a made up example obviously). I know I could use str.indexOf() for 1 and 2 to compare, but this presents the problem of it possibly returning -1.
Let me know what would be a good way to tackle this.
FYI: I am working in Java but I think this sort of indexOf function is pretty common in other languages.
I don’t know what degree of flexibility you require, but I would just do this the good-old-fashioned way of looping through the
String, something like this:Of course, this will return the
charit encounters first or 0 if neither neitherchars are found in the string.If you want to search for an arbitrary number of character: