2011-07-25 94 views
1

我想使用strstr函數來計算字符串'TT'在DNA序列ATGCTAGTATTTGGATAGATAGATAGATAGATAGATAGATAAAAAAATTTTTTTTT中出現的次數,而不計算任何'T的兩次。它應該出現5個'TT'實例,但是我的功能是給我9個,這就是如果你重疊TT的話你會得到什麼。我該如何解決這個問題,以便只計算'TT'的每個單獨實例並且沒有T被計數兩次?下面是我的程序:strstr()函數重疊字符串搜索

/***************************************************************************************/ 
#include <iostream>  
#include <cstring>  
#include <iomanip> 

using namespace std; 

    //FUNCTION PROTOTYPES 
    int overlap(char *ptr1, char *ptr2); 

int main() 
{ 

    //Declare and initialize objects 
    int count(0); // For DNA sequence 

     //DNA SEQUENCE 
    char DNA_sequence[] = "ATGCTAGTATTTGGATAGATAGATAGATAGATAGATAGATAAAAAAATTTTTTTT"; 
    char thymine_group[] = "TT"; 
    char *ptr1(DNA_sequence), *ptr2(thymine_group); 

//Send QUOTE to function 
count = overlap(ptr1, ptr2); 

    //Print number of occurences. 
    cout << "'TT' appears in DNA sequence " << count << " times" << endl; 
    return 0; 
} 

//FUNCTION 1 USING CHAR ARRAYS AND POINTERS 

int overlap(char *ptr1, char *ptr2) 
{ 
    int count(0); 
    //Count number of occurences of strg2 in strg1. 
    //While function strstr does not return NULL 
    //increment count and move ptr1 to next section 
    //of strg1. 
    while ((ptr1=strstr(ptr1,ptr2)) != NULL) 
    { 
     count++; 
     ptr1++; 
    } 
    return count; 
} 

/**************************************************************************************************/ 

回答

7

只要改變你的循環ptr1++;ptr1 += strlen(ptr2);

0

嘗試

int overlap(char *ptr1, char *ptr2) 
{ 
    int count(0); 
    //Count number of occurences of strg2 in strg1. 
    //While function strstr does not return NULL 
    //increment count and move ptr1 to next section 
    //of strg1. 
    while ((ptr1=strstr(ptr1,ptr2)) != NULL) 
    { 
     count++; 
     ptr1 += strlen (ptr2); 
    } 
    return count; 
} 
+0

簡單的天才!謝謝! – Arturo

+0

歡迎您:-) – Yahia

0
int count(char *haystack, char* needle) 
{  int c = 0; 
     for(;*haystack;haystack++){ 
      if(strcmp(haystack, needle)==0){ 
       c++; 
       haystack+=strlen(needle)-1; 
      } 
     } 
     return c; 
}