java.Contains(String search) method to be made in Java API ?

A

Alex Zorin

Well, I'm not having trouble or anything, but I'm wondering why the String
class doesnt have a contains method?

eg

public boolean contains(String str)

So you could write

if(myString.contains("poo" ) {
/ / Do whatever
}

Right now the only way to do this (or easiest at least) is to use
indexOf(String s) and see if the result isn't '-1'. So I propose:


public boolean contains(String full, String searched) {

if(full.indexOf(searched) != -1)
return true;

else { return false; }

}


Of course, you could make it so it extends the String class, but just an
example? I think this form of String manipulation would be most useful in
many cases..

Anyone else agree it'd be a useful addition?

}
 
T

Tor Iver Wilhelmsen

Alex Zorin said:
Well, I'm not having trouble or anything, but I'm wondering why the
String class doesnt have a contains method?

Because, as you argue yourself, the method would just be a
specialization of the general indexOf().

It's not useful to add specialized cases on top of generalized
methods; that only leads to library bloat.
 
T

tom bender

Intersting idea, but there may be a semantic difference which emans it
doesn't warrent it being made a contains method.
 
A

Alan Moore

Because, as you argue yourself, the method would just be a
specialization of the general indexOf().

It's not useful to add specialized cases on top of generalized
methods; that only leads to library bloat.

In jdk5.0, String has the new method: contains(CharSequence cs). So,
while it's still just a special case of indexOf(String s), it also
works with StringBuffer, StringBuilder, CharBuffer, and any other
class that implements CharSequence. Kind of a specialization and a
generalization at the same time.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,743
Messages
2,569,478
Members
44,898
Latest member
BlairH7607

Latest Threads

Top