Monday, August 9, 2010

String.contains and String.indexOf

To check if a string contains a substring, I usually use:

if(s.indexOf(sub) >= 0)
For JDK 5 or later, a contains method can also be used, which seems to be a little more readable:
if(s.contains(sub))
The signature of contains method is:
public boolean contains(java.lang.CharSequence s);
Note that CharSequence is a super-interface of String, StringBuffer, StringBuilder, java.nio.CharBuffer, javax.swing.text.Segment. So you can pass any of the 5 types to contains method.

The current implementation of contains method just convert the param to String and calls indexOf.

No comments: