gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 00:40:09 25 4
gpt4 key购买 nike

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com