Find first occurrence of two characters

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.

Answers


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:

public static char findFirstChar(String str, char c1, char c2) {
    for (char c : str.toCharArray())
        if (c == c1 || c == c2)
            return c;
    return 0;
}

Of course, this will return the char it encounters first or 0 if neither neither chars are found in the string.

If you want to search for an arbitrary number of character:

public static char findFirstChar(String str, char ... chars) {
    for (char c1 : str.toCharArray())
        for (char c2 : chars)
            if (c1 == c2)
                return c1;
    return 0;
}

I would say you should start by defining exactly what behavior you want. Assume your search terms are "1" and "2", what should be returned for each of the following strings?

  • "blah1blah2"
  • "blah2blah1"
  • "blahblah1"
  • "blahblah2"
  • "blahblah"

Write test cases for each of these, with your answer. Now make the tests pass. Simple!


Need Your Help

Make a very thin white line in CSS

css

This may sound quite silly, but I have no idea how to make a thin line smaller then 1px.

MySQL Database Sync

php mysql import

I have 2 MySQL databases with similar data. The difference is that one has an email column with about 2000 entries and the other has an email column with no entries. Is there some sort of bulk oper...