簡體   English   中英

strstr()函數重疊字符串搜索

[英]strstr() function overlapping string search

我正在嘗試使用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);

嘗試

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM