[英]How to express “if substring present in string do something” when using strstr?
I am trying to write a very simple program, which takes a string of characters(amino acids, or nucleic acids) and checks how many times a sub-string appears and outputs the result. 我正在尝试编写一个非常简单的程序,该程序需要一个字符串(氨基酸或核酸),并检查一个子字符串出现多少次并输出结果。
However, I don't know how to state in the while if loop to add 1 to count only if there has been a match and to brake if it reaches end of the line. 但是,我不知道如何在while if循环中声明加1以仅在存在匹配项时计数,并在到达行尾时制动。 Since the output of strstr is a pointer towards the position of the match, I can't figure out how to express string equivalence as a logical condition for the if(). 由于strstr的输出是指向匹配位置的指针,因此我无法弄清楚如何将字符串等价表示为if()的逻辑条件。
#include<stdio.h>
#include<string.h>
int main(){
int j,count;
char *i,dna_seq[50], desired_seq[3]="AT";
while(1){
printf("\nPlease insert protein sequence:\n");
gets(dna_seq);
printf("\nPlease insert searched sequence:\n");
gets(desired_seq);
while(1){
strstr(dna_seq,desired_seq);
if(//**answer**//);
count++;
dna_seq[j]++;
if(i=='\0') break;
}
printf("\n\nOccurance of %s: %d times\n",desired_seq,count);
}
} }
Also what would you write for debugging (since I am trying to practice)? 您还会为调试写什么(因为我正在尝试练习)?
Thank you in advance for the help, sorry if the question was not clearly posed. 预先感谢您的帮助,如果问题没有明确提出,对不起。
strstr
returns a pointer to the occurance of the string you're looking for, or NULL
if it's not present. strstr
返回一个指向您要查找的字符串的出现的指针,如果不存在则返回NULL
。 So you should loop until you get NULL
, and every time you get a valid pointer, increment the counter, and start looking from right after it: 因此,您应该循环执行直到获得NULL
,并且每次获得有效的指针时,都要递增计数器,然后从其后立即开始寻找:
char* loc = NULL;
while (loc = strstr(prot_seq,desired_seq)) {
count++;
loc++;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.