Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Which of the following ways is an efficient way of determining substring containment?

if (str.indexOf("/") > -1)

or

if (str.contains("/")) 
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
264 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


Edit:

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...