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

String is in String array or not ?

 
kri shan
Ranch Hand
Posts: 1460
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
How to find particular string value in the String array.

String[] names = new String[];
names[0] = joe;
names[1] = james;
names[2] = marry;

String person = "james";

How can I find whether james is in names String array or not ? Any API methods supports ?


 
Garrett Rowe
Ranch Hand
Posts: 1296
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There are no standard methods to search for a particular element in an unsorted array, but there are methods to search a sorted array. Alternatively you could convert the array to a List<String> using java.util.Arrays.asList() and use the List.contains() method. Or you could write your own linear search method.
 
Michal Winther
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
kri shan wrote:How to find particular string value in the String array.

String[] names = new String[];
names[0] = joe;
names[1] = james;
names[2] = marry;

String person = "james";

How can I find whether james is in names String array or not ? Any API methods supports ?




Pretty simple:

Use the Strings own compare function: equals() or equalsIgnoreCase().
Both return boolean.

Example:

for(int i=0; i<names.length; i++){
if(names[i].equalsIgnoreCase(person)) return true;
}>
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic