1

strstr 関数を使用して、「T」を 2 回カウントせずに、文字列「TT」が DNA シーケンス ATGCTAGTATTTGGATAGATAGATAGATAGATAGATAGATAAAAAAATTTTTTTT に出現する回数をカウントしようとしています。'TT' の 5 つのインスタンスが表示されるはずですが、代わりに私の関数は 9 を返しています。「TT」の個々のインスタンスのみがカウントされ、T が 2 回カウントされないようにするにはどうすればよいですか? これが私のプログラムです:

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

/**************************************************************************************************/
4

3 に答える 3

7

ptr1++;ループを次のように変更するだけですptr1 += strlen(ptr2);

于 2011-07-25T01:18:18.427 に答える
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;
}
于 2011-07-25T01:19:15.027 に答える
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;
}
于 2011-07-25T01:22:56.133 に答える