获取某个字符串元素java的最后一个索引?

问题描述:

有一个已经写好的方法的索引,但是我如何使用它来查找数组中某个字符串的最后一个实例?获取某个字符串元素java的最后一个索引?

public int indexOf(String string) { 
    if (string == null) { 
     throw new NullPointerException(); 
    } 
    for (int index = 0; index < size; index++) { 
     if (string.equals(strings[index])) { 
      return index; 
     } 
    } 
    return -1; 
+0

'string.equals(字符串[指数])'其中是从哪里来的? – EvenPrime 2014-09-19 15:05:42

+0

这就是字符串数组:) :) – 2014-09-19 15:11:53

反转循环并从数组末尾开始。

public int indexOf(String string) { 
    if (string == null) { 
     throw new NullPointerException(); 
    } 
    for (int index = size-1; index >= 0; index--) { 
     if (string.equals(strings[index])) { 
      return index; 
     } 
    } 
    return -1; 
} 
+0

这是OP想要的吗?他允许修改方法吗?.. – dasblinkenlight 2014-09-19 14:59:11

Java字符串也有一个lastIndexOf方法,您可以使用。

+0

这适用于字符串,不适用于字符串数组。 – Narmer 2014-09-19 15:13:52

String.lastIndexOf 

String.lastIndexOf(String str, int fromIndex) 
+1

这适用于字符串,不适用于字符串数组。 – Narmer 2014-09-19 15:13:33

+0

啊我现在得到它 – 2014-09-19 16:31:10

尝试存储索引并返回它:

int lastIndex = -1; 
for (int index = 0; index < size; index++) { 
    if (string.equals(strings[index])) { 
     lastIndex = index; 
    } 
} 
return lastIndex; 

从Cattwood的答复应该是在这种情况下更有效。

创建一个lastIndexOf方法并向后迭代数组。也就是说,像 -

public int lastIndexOf(String string) { 
    if (string == null) { 
    throw new NullPointerException(); 
    } 
    for (int index = strings.length - 1; index >= 0; index--) { 
    if (string.equals(strings[index])) { 
     return index; 
    } 
    } 
    return -1; 
} 

怎么样简单的答案

阵列legth的getthe大小。

ArrayList arry = new ArrayList()<String>; 
if(arry!=null) { 
int last = arry.legth() -1 ; 
//no loop proudly 
arr[last]; 
return last ; 
} 
+0

我认为这不是OP所要求的。他想要特定字符串的最后一个_ccurence_。 – Narmer 2014-09-19 15:02:10

如果不能修改该方法也没有创建一个新的,你必须扭转阵列和在反向操作:

ArrayUtils.reverse(strings); 
int reverseIndex = indexOf("myString"); 
int realIndex = reverseIndex > 0 ? strings.length - (reverseIndex + 1) : -1; 
ArrayUtils.reverse(strings); //Back to normal