• Post Reply Bookmark Topic Watch Topic
  • New Topic

Searching within a vector...  RSS feed

 
Ronnie McBob
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi all,

I am using a Vector to store lots of Strings.

There is a "contains" method from the List interface that Vector implements...

This currently does a .equals comparison so I can find Strings where I know what the exact String looks like.

However, is there an easy way that I can do something like:

if the Vector contains the following:
"abc"
"def"
"ghi"
"jkl"

I can try to find "ab" it still returns true... because "ab" is a substring of one of the Objects in the vector...

Thanks for any hints an tips!

Ron
 
Nigel Browne
Ranch Hand
Posts: 704
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Read up on Regular Expressions
 
Julia Reynolds
Ranch Hand
Posts: 123
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ron,

Here is a method that searches a vector and returns
a vector containing all the objects which match the search criteria.
It uses regex via the Pattern object.


public Vector searchRows(String columnKey, String searchString){
Vector foundRows = new Vector();
Vector allRows = getTableRows();
for(int i=0; i<allRows.size(); i++){
String columnValue = (String)((Hashtable)allRows.get(i)).get(columnKey);
Pattern p = Pattern.compile(searchString, Pattern.CASE_INSENSITIVE);

if( p.matcher(columnValue).matches())
{
foundRows.add(allRows.get(i));
}
}

return foundRows;
}//end searchRows(String columnKey, String searchString)


I call the method like this:

Vector matches = searchRows("Status",".*Arrive.*Inbound.*");

(That '.*' is a wild card.)

Cheers,

Julia

P.S. Obviously, my vector has hashtables and so i have to pass in the hashtable key to get objects to be searched. You can see that this method could be simplified to just search strings in a vector.

[ December 15, 2004: Message edited by: Julia Reynolds ]
[ December 15, 2004: Message edited by: Julia Reynolds ]
 
Ronnie McBob
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Nigel & Julia,

Thanks for the link and the example.

I'm going to look through the items that you've given me.

Thanks for the pointers!

Ron
 
Layne Lund
Ranch Hand
Posts: 3061
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Julia Reynolds:
Ron,

Here is a method that searches a vector and returns
a vector containing all the objects which match the search criteria.

What if you need to know the index of the object in the original vector? Or are you leaving this as the proverbial exercise for the reader?
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!