使用 StringBuilder.indexOf() 获取出现的字符串的所有位置

Getting all positions of an occuring String using StringBuilder.indexOf()

Java 初学者过来。 我目前正在研究一个搜索人类 DNA 一部分的程序。 具体来说,我想使用 StringBuilder.indexOf() 在 StingBuilder 中查找所有出现的字符串。但我需要所有事件,而不仅仅是第一次。

代码:

public void search(String motive){
    int count = 0;
    gene.indexOf(motive);   // gene is the Stringbuilder
    count++;


}

我需要基因 StringBuilder 中出现的所有动机以及动机在基因中出现的频率计数器。 任何帮助,因为 indexOf() 只显示第一次出现?

我认为您正在寻找基因序列或子序列中特定核苷酸序列的索引。以下示例 class 演示了使用 Java 的正则表达式库查找此类内容的通用方法:

package jcc.tj.dnamatch;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Gene {
   private String gene;

   public Gene() {}

   public Gene( String gene ) {
      this.gene = gene;
   }

   public List<Integer> find( String seq ) {
      List<Integer> indices = new ArrayList<Integer>();

      Pattern pat = Pattern.compile( seq );
      Matcher m = pat.matcher( gene );

      while ( m.find() )
         indices.add( m.start() );

      return indices;
   }

   public String getGene() {
      return gene;
   }

   public void setGene( String gene ) {
      this.gene = gene;
   }
}

上面的例子,使用了Matcher来寻找模式。还有其他基于字符串的算法可能更有效,但作为起点,Matcher 为任何类型的文本模式搜索提供了通用解决方案。

将核苷酸编码为字符 (ATCG) 非常灵活方便,允许使用基于字符串的工具来分析和表征序列 and/or 子序列。不幸的是,它们不能很好地扩展。在这种情况下,最好考虑使用更具体的生物信息学技术来表示和管理序列。

本书 Next Generation Sequencing Technologies and Challenges in Sequence Assembly. A more detailed PDF preview of it is available from this Google link 的第 2 章 – 下一代测序中的算法和数据结构是某些技术的很好参考;虽然我不保证它永远有效。

您可能还想看看 BioJava. While, I wouldn't want to detract you from Java, Perl is another good alternative for sequence analysis. Beginning Perl for Bioinformatics; Perl and Bioinformatics; or BioPerl

我意识到这个答案可能是TMI;但是,如果它能帮助您或其他人找到更合适的解决方案,那么它就达到了目的。

编辑:

根据下面的评论,这似乎是一道家庭作业题,因为 要求在 StringBuilder.indexOf() 之前完成搜索。以下方法将相应地完成搜索。

public List<Integer> findBySb( String seq ) {
    List<Integer> indices = new ArrayList<Integer>();
    StringBuilder sb = new StringBuilder( gene );
    int strIdx = 0;

    while ( strIdx < sb.length() ) {
        int idx = sb.indexOf( seq, strIdx );
        if ( idx == -1 )
            break;
        indices.add( idx );
        strIdx = idx + seq.length();
    }

    return indices;
}

相同的 indexOf() 方法可以直接与字符串一起使用。

public List<Integer> findByString( String seq ) {
    List<Integer> indices = new ArrayList<Integer>();
    int strIdx = 0;

    while ( strIdx < gene.length() ) {
        int idx = gene.indexOf( seq, strIdx );
        if ( idx == -1 )
            break;
        indices.add( idx );
        strIdx = idx + seq.length();
    }

    return indices;
}

StringBuilderString都使用String.indexOf()的相同静态实现,因此在功能上没有区别。然而, 仅仅为了搜索而实例化一个 StringBuilder 有点矫枉过正 更浪费,因为它还分配缓冲区来管理字符串操作。我可以继续 :),但这并没有增加答案。