Which of the following ways is an efficient way of determining substring containment?
if (str.indexOf("/") > -1)
or
if (str.contains("/"))
Take a look at the java.lang.String
source code. The contains
method is implemented using a call to indexOf
, so they are essentially the same.
public boolean contains(CharSequence s) {
return indexOf(s.toString()) > -1;
}
You should use whichever method makes your code more readable. If you are checking to see if a String contains a specific substring, use contains
. If you are looking for the substring's starting index, use indexOf
.
A couple of answers mention that indexOf
should be preferred over contains
due to the fact that contains
makes an additional method call, and is thus, less efficient. This is wrong. The overhead caused by an additional method call in this case is totally insignificant. Use whichever method makes the most sense in the context of your implementation. This will make your code more readable.