File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Beginning Java and the fly likes Comparing to a large number a strings? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Comparing to a large number a strings?" Watch "Comparing to a large number a strings?" New topic
Author

Comparing to a large number a strings?

Tim Chaung
Greenhorn

Joined: Sep 19, 2011
Posts: 17
Is there a way to compare a large quantity of strings? Such as if you were to see if the user input string was a valid pet.

Is there a way to compare it to "dog" "cat" "bird" etc without using A LOT of if statements?

I could use string.split but then how exactly is that stored in an array?
fred rosenberger
lowercase baba
Bartender

Joined: Oct 02, 2003
Posts: 11499
    
  16

somewhere, you're going to have to build all the string you want to compare against. I would consider putting all of them in a set. Then, when you get your new string, you just check to see if it is already in there.


There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors
Cody Hey
Greenhorn

Joined: Sep 24, 2011
Posts: 4
May be kind of late but...

Switch(string name){
case "dog":
System.out.println(string name);
Break;
Case "cat":
System.out.println("kitten");
Break; }

This takes the variable (your string) and in the case that it equals "dog" it performs the code until it gets to "break;"
It's basically a lot of if statements.
Zandis Murāns
Ranch Hand

Joined: Aug 18, 2009
Posts: 174

I think switching strings is possible only in java 7.
Anyways, I thing the best solution is regex:

Javin Paul
Ranch Hand

Joined: Oct 15, 2010
Posts: 294


If you need to compare multiple strings , try using regex as suggested by Zandis, regex is best for string matching and many methods in string e.g. replace, split etc support regex.


SQL Query Interview Question
fred rosenberger
lowercase baba
Bartender

Joined: Oct 02, 2003
Posts: 11499
    
  16

i guess the question is:

do you need to compare a lot of user inputs to a few possible string, or so you need to compare a few user input strings to a large list of possible strings?

I would approach these differently.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Comparing to a large number a strings?