开发者

strstr() function overlapping string search

I am trying to use the strstr function to count the number of times the string 'TT' appears in the DNA sequence ATGCTAGTATTTGGATAGATAGATAGATAGATAGATAGATAAAAAAATTTTTTTT without counting any 'T's twice. It should come out with 5 instances of 'TT' but instead my function is giving me 9, which is what you would get if you overlapped the 'TT's. How can I fix this so that only each individual instance of 'TT' is counted and no T is counted twice? Here is my program:

/***************************************************************************************/
#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 " 开发者_Python百科<< 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;
}

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


Just change ptr1++; in your loop to ptr1 += strlen(ptr2);


try

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;
}


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜