2014-09-04 39 views
0

我想解决一个java中数组的复杂问题。复杂的数组任务

它以字符串开头。

String text = "I am the best Programmmer in the world the best"; 

String [] arraytext = text.split(""); 

下得遍历数组和检查记录

for (String array1 : arraytext) { 
     System.out.println(array1); 
      } 

这工作,我有我的数组

我现在已经是检查数组的一个记录的问题,获取数组的索引。

我的意思是

for (String array1 : arraytext) { 
    if (array1.equalsIgnoreCase("best")){ 
      // get the index of this array 

      } 
     } 

我需要得到该数组的索引d。它非常复杂,因为我实际上需要最好的第二个实例的索引。

并从for循环中获取此索引的结果。

真的会感谢所有帮助

+0

所以基本上你只是想在二审指数? – user2548635 2014-09-04 15:55:42

+0

你需要传递一个字符串到分隔符(这是字符串将被拆分)的split()方法 – steven35 2014-09-04 15:56:01

回答

3

的第一件事就是正确地分割你的字符串,你可能想拆就要么" "或使用正则表达式来检查是否有更广泛的空白列表。

然后,所有你需要做的就是创建做搜索看起来像这样的方法:

int findIndex(String str, int start, String[] array) { 
    for (int i=start;i<array.length;i++) { 
     if (array[i].equals(str)) { 
      return i; 
     } 
    } 
    return -1; 
} 

然后让你第一次做:

index = findIndex("test", 0, array); 

为你做的第二:

index = findIndex("test", index+1, array); 

如果没有发现任何内容,则索引将为-1。

+0

不错,你是一个真正的..感谢一堆 – 2014-09-04 16:33:46

0

怎么样在

for(int i = 0; i < arraytext.length ; i++){ 
    if(arrayText[i].equalsIgnoreCase("best")) 
     System.out.println(i); 
} 
+0

谢谢这打印出索引3的结果和9,现在请我所需要的是这9次的结果,这是最好的第二次。我需要这个9 for the loop – 2014-09-04 16:19:57

+0

你可以投入一个新变量BEFORE for循环,比如'int index = 0;'然后是for循环,然后代替'System.out.println(i)'你可以写'index = i;'然后当你在循环之外时,你可以访问包含被搜索单词索引的i – Lucarnosky 2014-09-04 16:22:01

0

Java的语法的foreach改变for循环围绕for环路只是语法糖。如果您想查找最后一个匹配元素,最简单的方法是自己手动编写for循环,但是向后迭代。像这样的东西。

for (int i = arraytext.length - 1; i >= 0; i--) 
{ 
    if (arraytext[i].equalsIgnoreCase("best")) 
    { 
     // i is the array index you're looking for, do something with it 
     break; // or return if this is a method 
    } 
} 
0

您可以使用ArrayUtils:

import org.apache.commons.lang.ArrayUtils; 
int index = ArrayUtils.lastIndexOf(arraytext, "best");