This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
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


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
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: 11153
    
  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: 281


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.


http://javarevisited.blogspot.com - java classpath - Java67 - java hashmap - java logging tips java interview questions Java Enum Tutorial
fred rosenberger
lowercase baba
Bartender

Joined: Oct 02, 2003
Posts: 11153
    
  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?
 
Similar Threads
BufferedReader
Compare Content of StringBuilder
Comparing Strings
string question .explanation pls
What is the representation of the empty line?