我正在尝试使用strstr函数计算字符串“TT”出现在DNA序列ATGCTAGTATTTGGATAGATAGATAGATAGATAGATAGATAAAAAAATTTTTTTTTT中的次数,而没有两次计数任何“T”。它应该带有5个“TT”的实例,但是我的功能是给我9,这是您重叠“TT”后得到的结果。我该如何解决这个问题,以便仅对每个“TT”实例进行计数,而对T则不进行两次计数?这是我的程序:

/***************************************************************************************/
#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;
}

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

最佳答案

只需将循环中的ptr1++;更改为ptr1 += strlen(ptr2);

关于c++ - strstr()函数重叠字符串搜索,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/6810925/

10-13 08:29