[英]How to find array ID?
如何找到陣列ID?
例如:
String[] ar = {"ABC","EFG","HIJ"};
當搜索字符串為“ A”並顯示ABC時,如何了解數組中的哪個位置具有ABC( ar[n]
,如何查找ABC n?)
for (int i = 0; i < ar.length; i++) {
if (ar[i].contains("A")) {
System.out.println("found an element: " + ar[i] + " at index " + i);
}
}
要查找以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]);
}
}
要查找包含 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]);
}
}
您可以在其他答案中使用該選項,也可以僅使用ArrayList。 ArrayList是動態的,您可以調用indexOf()方法並傳遞“ ABC”。 如果不存在“ ABC”,則返回-1,否則返回“ ABC”的索引。 :)
如果即時通訊正確理解您正在嘗試通過字符串查找索引(而不是ID)。 例如,您知道“ EFG”。
可以使用以下代碼:
String[] str = {"ABC", "EFG", "HIJ"};
int index = 0;
for(int i = 0; i < str.length; i++) {
if(str[i].equals("EFG")) {
index = i;
}
}
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);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.