Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
JavaRanch.com/granny.jsp
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

compare??

 
Suka Hati
Ranch Hand
Posts: 56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi,
can somebody tell me how to check whether a string is one of the element in a string array.

eg: i have a string("a").i want to check whether String[] check = new String(xx) have "a" as one of it element...
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Basically -- if I understand you correctly -- you can either: Loop through the array and compare each element to your target String (using the equals method); or use the sort and binarySearch methods from the Arrays class in java.util.

See the API for Arrays...
http://java.sun.com/j2se/1.5.0/docs/api/java/util/Arrays.html

Can you tell us more about what you're trying to do and how you've tried to do it?
 
Jimmy Die
Ranch Hand
Posts: 97
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

I'm not sure what was written was actual code or some psudocode?

String[] check = new String(xx)

If you want to compare strings use the equals() method from the String class.

String[] myString = {"A", "a", "B", "b"}; // array of 4 strings
String testString = "b";

then loop through your string array checking each array element against the testString

example check

myString[0].equals(testString) // false

Cheers
 
Suka Hati
Ranch Hand
Posts: 56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
how if i want to instatiate all the element in that array(a) as a single String(aString)..

e.g:
a[0]=cat
a[1]=eat
a[2]=fish

aString = "cat eat fish"

i try to do like below....but fail...

for (int i=0; i<bil; i++){
output = output+testArray[i];
 
Layne Lund
Ranch Hand
Posts: 3061
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Suka Hati:
how if i want to instatiate all the element in that array(a) as a single String(aString)..

e.g:
a[0]=cat
a[1]=eat
a[2]=fish

aString = "cat eat fish"

i try to do like below....but fail...

for (int i=0; i<bil; i++){
output = output+testArray[i];


What do you mean that you fail? Does the above code compile? If not what errors do you get? If so, what does it do? How does the output differ from what you expect?

If you can provide answers to these questions, we can help you along the way. Details like these are crucial when trying to diagnose ANY problem, but are even more important when it comes to computer programming.

Layne
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic