Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Comparing to a large number a strings?

 
Tim Chaung
Greenhorn
Posts: 17
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 12087
29
Chrome Java Linux
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Cody Hey
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 174
Java Java ME Opera
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think switching strings is possible only in java 7.
Anyways, I thing the best solution is regex:

 
Javin Paul
Ranch Hand
Posts: 295
Eclipse IDE Firefox Browser Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

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.
 
fred rosenberger
lowercase baba
Bartender
Posts: 12087
29
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic