This week's book giveaway is in the Clojure forum.
We're giving away four copies of Clojure in Action and have Amit Rathore and Francis Avila on-line!
See this thread for details.
Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Comparing to a large number a strings?

 
Tim Chaung
Greenhorn
Posts: 17
  • 0
  • 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
Pie
Posts: 12021
25
Chrome Java Linux
  • 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
  • 0
  • 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
  • 0
  • 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
  • 0
  • 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
Pie
Posts: 12021
25
Chrome Java Linux
  • 0
  • 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.
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic