Find the index value of a character stored in arraylist
I have a string arraylist
. Need to get the index values of all elements if its value equals a specific character.
For eg need to get the index value of el开发者_如何学Cement if its value = "."
with indexOf()
& lastIndexOf()
i am able to find only the index value of 1st and last occurrence respectively.
ArrayList<String> als_data = new ArrayList<String>();
als_data[0] = "a"
als_data[1] = "b"
als_data[2] = "a"
als_data[3] = "c"
als_data[4] = "d"
als_data[5] = "a"
now i need to find the indices of "a"
my output should be like
0
2
5
please help me out in doing this.
String string = "a.b.cc.dddd.ef";
int index = 0;
while((index = string.indexOf('.', index)) != -1) {
index = string.indexOf('.', index);
System.out.println(index);
index++;
}
prints
1
3
6
11
If you want to do the same over a list,
List<String> list = new ArrayList<String>();
list.add("aa.bb.cc.dd");
list.add("aa.bb");
list.add("aa.bbcc.dd");
for (String str : list) {
printIndexes(str, '.');
System.out.println();
}
private void printIndexes(String string, char ch) {
int index = 0;
while((index = string.indexOf(ch, index)) != -1) {
index = string.indexOf(ch, index);
System.out.println(index);
index++;
}
}
will print
2
5
8
2
2
7
EDIT: Update after the author clarified his question
List<String> list = new ArrayList<String>();
list.add("abcd");
list.add("pqrs");
list.add("abcd");
list.add("xyz");
list.add("lmn");
List<Integer> indices = new ArrayList<Integer>();
for (int i = 0; i < list.size(); i++) {
if("abcd".equals(list.get(i))) {
indices.add(i);
}
}
System.out.println(indices);
It's simple and stringh forword .
int index=list.indexOf(vale);
Now returns found index value ;
well... you can easily do this linearly with a loop:
private int[] getIndexe(String searchFor,List<String> sourceArray) {
List<Integer> intArray = new ArrayList<Integer>();
int index = 0;
for(String val:sourceArray) {
if(val.equals(searchFor)) {
intArray.add(index);
}
index++;
}
return intArray.toArray(new int[intArray.size()]);
}
/// I haven't tried compiling or running the above, but it should get you close. Good luck.
Use String.indexOf( mychar, fromIndex)
.
Iterate starting with fromIndex 0, then use the previous result as your fromIndex until you get a -1.
精彩评论