3

So let's say I have an array of Strings of the following type

something **foo**garblesomething somethingelse
something **foobar**blahblah somethingelse
and so on

So essentially data are triples

Now, in the middle part of the string

Notice keywords "foo" and "foobar"

What I want to do is:

if "foo" in string:
    return 1
else if "foobar" in string:
    return 2
else -1

How do I do this in Java?

4
  • A less contrived example might help - for example to solve this exact problem you could just search for "foobar" first, and if it isn't found, search for "foo". Commented Aug 22, 2013 at 19:08
  • 5
    The specific method to use would be contains(). There's no reason to use a regex. Commented Aug 22, 2013 at 19:09
  • contains() Commented Aug 22, 2013 at 19:10
  • There is absolutely no need for a regex in this situation. Opting to use a regex will do nothing but make your code less efficient and more difficult to maintain. Commented Aug 22, 2013 at 19:15

1 Answer 1

8

Just use String#contains(String)

if (str.contains("foobar"))
    return 2;
else if (str.contains("foo"))
    return 1;
else
    return -1;

Important to check for foobar before foo otherwise it will return 1 for both cases.

Sign up to request clarification or add additional context in comments.

Comments

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.