【问题标题】:How do I search and tally up a string "CTG" in another string which is a file? [duplicate]如何在另一个文件字符串中搜索和统计字符串“CTG”? [复制]
【发布时间】:2015-12-29 05:09:02
【问题描述】:

如何从作为字符串读取的文件中搜索字符串 CTG?然后数一数它出现了多少次? 例如,我将如何在此处或一般任何地方添加代码来执行此操作:

public String readStrFromFile(){

    FileResource readFile = new FileResource();

    String DNA = readFile.asString();

    //System.out.println("DNA: " + DNA);

    return DNA;

}//end readStrFromFile() method;

【问题讨论】:

    标签: java string


    【解决方案1】:

    你可以使用正则表达式

    String DNA = readFile.asString();
    Pattern pattern = Pattern.compile("CTG");
    Matcher matcher = pattern.matcher(DNA);
    while(matcher.find()){
        System.out.println(matcher.group() + " at " + matcher.start());
    }
    

    或者如果文件太大,你应该使用KMP算法或类似的。

    编辑:
    你可以有一个柜台。

    int count = 0; 
    while(matcher.find()){
        count++;
        System.out.println(matcher.group() + " at " + matcher.start());
    }
    System.out.println("Number of count : " + count);
    

    【讨论】:

    • 我将如何计算所有这些 CTG?我需要知道有多少。
    • @TakaroSpike 你可以使用计数器。
    猜你喜欢
    • 2012-03-05
    • 2021-11-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-18
    • 1970-01-01
    • 2013-08-08
    相关资源
    最近更新 更多