Is there any situation where
if (str1.contains(str2)) {}
and
if (str1.indexOf(str2)>=0) ) {}
might be different?
A colleague has been changing all occurrences of the 1st form for the 2nd. But I don't see the reason and I can't ask him.
Welcome to the Java Programming Forums
The professional, friendly Java community. 21,500 members and growing!
The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.
>> REGISTER NOW TO START POSTING
Members have full access to the forums. Advertisements are removed for registered users.
Is there any situation where
if (str1.contains(str2)) {}
and
if (str1.indexOf(str2)>=0) ) {}
might be different?
A colleague has been changing all occurrences of the 1st form for the 2nd. But I don't see the reason and I can't ask him.
Firstly welcome to Java Programming Forums
As far as im aware .contains() is a newer method that is just a specialized case of indexOf()
mgrootsch (September 21st, 2009)
First off, contains returns true/false while indexOf will return the index of the search.
But the magic is in the contains method, you ready for this, its a funny one
public boolean contains(CharSequence s) { return indexOf(s.toString()) > -1; }
// Json
mgrootsch (September 21st, 2009)
Better practice, maybe... But hardly worth the trouble of having to check all those differences that light up in CVS (in my opinion).
Thanks for the replies.
Marcel
The methods have different use, if you need to check if the String contains something then use the contains, but if you want to know where in the String it is contained, use the indexOf method.
// Json