2

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 element 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.

4

4 回答 4

9
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++;
}

印刷

1
3
6
11

如果你想对一个列表做同样的事情,

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++;
    }
}

将打印

2
5
8

2

2
7

编辑:作者澄清他的问题后更新

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);
于 2011-03-08T18:16:33.180 回答
4

这很简单,而且 stringh forword 。

int index=list.indexOf(vale);

现在返回找到的索引值;

于 2013-05-31T05:00:16.367 回答
1

嗯......你可以很容易地用一个循环线性地做到这一点:

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()]);
}

/// 我没有尝试编译或运行上面的,但它应该让你接近。祝你好运。

于 2011-03-08T18:14:15.120 回答
0

使用String.indexOf( mychar, fromIndex).

从 fromIndex 0 开始迭代,然后使用之前的结果作为 fromIndex,直到得到 -1。

于 2011-03-08T18:14:11.983 回答