2013-02-24 56 views
0

如何查找數組ID?如何查找數組ID?

例如:

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

當搜索字符串將是「A」,它會顯示ABC,但如何理解什麼地方在陣列有ABC

ar[n],如何找到ABC N 2)
+0

可能重複:http://stackoverflow.com/questions/4962361/where -is-javas-array-indexof – adamdunson 2013-02-24 18:27:24

+0

你的數組是否被排序(如你的例子所示)? – 2013-02-24 18:28:14

回答

4

要查找與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]); 
    } 
} 

要查找元素包含答:

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

搜索字符串是'A'而不是ABC – exexzian 2013-02-24 18:28:53

+0

+1現在它會起作用 – exexzian 2013-02-24 18:31:58

5
for (int i = 0; i < ar.length; i++) { 
    if (ar[i].contains("A")) { 
     System.out.println("found an element: " + ar[i] + " at index " + i); 
    } 
} 
0

您可以使用該選項在其他的答案,或者你可以簡單地使用ArrayList。 ArrayLists是動態的,你可以調用indexOf()方法並傳入「ABC」。如果「ABC」不存在,或者「ABC」的索引,這將返回-1。 :)

1

如果我正確理解你正在嘗試通過String找到索引(不是ID)。例如,你知道「EFG」。

Fot的,你可以使用代碼:

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

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

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

應該是: -

for(int i = 0; i < ar.length; i++){ 
     if(ar[i].startsWith("A")){ 
      System.out.println("Found in index " + i); 
     } 
} 
+0

這是一個循環的完美示例,它不允許知道找到的元素的索引,這正是OP所要求的。 – 2013-02-24 18:48:42

+0

我認爲它不應該是增強循環,因爲你不能得到索引,沒有注意到在問題中。 – tmwanik 2013-02-24 18:52:02