使用indexOf查找多个匹配

时间:2014-01-15 12:15:24

标签: java indexof

我希望使用indexOf方法找到多个匹配。

我有这条线要搜索:

public static final String DNA = "ATGTTGCTGGCATAGATGTTAACTTCCAC";

例如,我想在此字符串中搜索AC的位置。我想用这种方法做到这一点。目前我只有21次。因为我应该得到21和27个。

public int[] zoek(String gezocht)
{
    // goed = 21+27 bij AC
    int fromIndex = 0;
    for (int i = 0; i < DNA.length(); i++)
    {
       fromIndex = DNA.indexOf(gezocht, fromIndex);
       dna.add(fromIndex);

    }
    System.out.println(dna);
    return zoek;
}

3 个答案:

答案 0 :(得分:0)

使用while循环,例如:

int fromIndex = 0;
while((fromIndex = dna.indexOf(gezocht, fromIndex)) != -1) {
    ...
    fromIndex++; // We don't want to find the previous match again
}

答案 1 :(得分:0)

您必须向fromIndex添加一个,以便indexOf不会再次找到相同的匹配项。你也不应该循环任何次数,因为字符串有字符,但只要找到出现次数:

int fromIndex = -1;
while ((fromIndex = DNA.indexOf(gezocht, fromIndex + 1)) != -1) {
   dna.add(fromIndex);
}

答案 2 :(得分:0)

试试这段代码。

import java.util.ArrayList;

public class Test001
{
    public static final String DNA = "ATGTTGCTGGCATAGATGTTAACTTCCAC";

    public static Integer[] zoek(String gezocht)
    {
        ArrayList<Integer> dna = new ArrayList<Integer>();
        int i = 0;
        while (i < DNA.length())
        {
           int fromIndex = DNA.indexOf(gezocht, i);
           if (fromIndex >= 0){
               dna.add(fromIndex);
               i = fromIndex + 1;
           }else{
               break;
           }
        }
        System.out.println(dna);
        Integer[] zoek = new Integer[dna.size()]; 
        return dna.toArray(zoek);
    }

    public static void main(String args[]) {
        Integer[] ind = zoek("AC");
        for (int fromIndex : ind){
            System.out.println(fromIndex);
        }
    }
}

我会以不同的方式命名变量btw。

import java.util.ArrayList;

public class Test001
{
    public static final String DNA = "ATGTTGCTGGCATAGATGTTAACTTCCAC";

    public static Integer[] search(String sought)
    {
        ArrayList<Integer> hits = new ArrayList<Integer>();
        int startIndex = 0;
        while (startIndex < DNA.length())
        {
           int foundIndex = DNA.indexOf(sought, startIndex);
           if (foundIndex >= 0){
               hits.add(foundIndex);
               startIndex = foundIndex + 1;
           }else{
               break;
           }
        }
        System.out.println(hits);
        Integer[] found = new Integer[hits.size()]; 
        return hits.toArray(found);
    }

    public static void main(String args[]) {
        Integer[] found = search("AC");
        for (int foundIndex : found){
            System.out.println(foundIndex);
        }
    }
}