strstr()函数重叠字符串搜索

时间:2011-07-25 01:14:06

标签: c++ string overlap strstr

我正在尝试使用strstr函数计算字符串'TT'出现在DNA序列ATGCTAGTATTTGGATAGATAGAGAGATAGATAGATAGATAAAAAAATTTTTTTT中的次数,而不计算任何'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;
}

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

3 个答案:

答案 0 :(得分:7)

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

即可

答案 1 :(得分: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;
}

答案 2 :(得分: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;
}