0

How to find array ID ?

for example:

String[] ar = {"ABC","EFG","HIJ"};

When search string will be "A" and it will show ABC but how to understand what Place in array has ABC (ar[n], how to find ABC n ?)

5 Answers5

4
for (int i = 0; i < ar.length; i++) {
    if (ar[i].contains("A")) {
        System.out.println("found an element: " + ar[i] + " at index " + i);
    }
}
JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
3

To find elements that starts with A:

for (int index = 0; index < ar.length; index++) {
  if (ar[index].startsWith("A")) {
    System.out.println("Found an element on array that starts with 'A': " + ar[index]);
  }
}

To find elements that contains A:

for (int index = 0; index < ar.length; index++) {
  if (ar[index].contains("A")) {
    System.out.println("Found an element on array that contains 'A': " + ar[index]);
  }
}
0

You can use the option in the other answer, or you can simply use an ArrayList. ArrayLists are dynamic, and you can call the indexOf() method and pass in "ABC". This will either return -1, if "ABC" is not present, or the index of "ABC". :)

christopher
  • 26,815
  • 5
  • 55
  • 89
0

If im understanding correctly you're trying to find the index (not ID) by String. For example, you know "EFG".

Fot that you can use the code:

String[] str = {"ABC", "EFG", "HIJ"};

int index = 0;
for(int i = 0; i < str.length; i++) {
    if(str[i].equals("EFG")) {
        index = i;
    }
}
Stef
  • 1
  • 1
-1

for (String s : ar) { if (s.startsWith("A")) {/* You code here */}}

Should be :-

for(int i = 0; i < ar.length; i++){
        if(ar[i].startsWith("A")){
            System.out.println("Found in index " + i);
        }
}
tmwanik
  • 1,643
  • 14
  • 20
  • That's a perfect example of a loop which doesn't allow to know the index of the found element, which is precisely what the OP is asking. – JB Nizet Feb 24 '13 at 18:48
  • I think it should not be the enhanced loop, since you cannot get the index, did not notice that in the question. – tmwanik Feb 24 '13 at 18:52