java 获取字符串数组android中的项目位置?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30440463/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get item positions in string array android?
提问by Lukas Anda
Let's say I have an array like this:
假设我有一个这样的数组:
String[] = {
"#abc #def",
"#abc",
"#def",
"#xyz #def"
}
My question is I want to search for specific character or string like "#abc" or "a" and get their positions in the array.
我的问题是我想搜索诸如“#abc”或“a”之类的特定字符或字符串并获取它们在数组中的位置。
回答by Luke
Just loop through it and check each string yourself
只需遍历它并自己检查每个字符串
for(int i=0; i < array.length; i++)
if(array[i].contains("#abc"))
aPosition = i;
If you want to store multiple positions, you'll need a mutable array of some sort such as a List
, so instead of aPosition = i
you'll have list.add(i)
如果要存储多个位置,则需要某种可变数组,例如 a List
,因此aPosition = i
您将拥有list.add(i)
回答by Ahamadullah Saikat
String[] values = { "1a", "2a", "3a"};
int pos = new ArrayList<String>(Arrays.asList(values)).indexOf("3a");
回答by Ahmad Sanie
let's call your array of strings s, the code will be:
String[] s={"#abc #def",
"#abc",
"#def",
"#xyz #def"};
int count=0;
for(String s1:s){
if(s1.contains("#abc")){
//do what ever you want
System.out.println("Found at: "+count);
break;
}
count++;
}
hope this will work for you.
希望这对你有用。
回答by Gabriella Angelova
Use indexOf
利用 indexOf
String[] myList = {
"#abc #def",
"#abc",
"#def",
"#xyz #def"
};
int index = myList.indexOf("#abc");
and in the index
variable you become the index of the searched element in your array
在index
变量中,您将成为数组中搜索元素的索引
回答by zond
you can use ArrayUtils
你可以使用 ArrayUtils
String[] myList = { "#abc #def", "#abc", "#def", "#xyz #def" };
int index = ArrayUtils.indexOf(myList,"#def");