簡體   English   中英

使用strstr時如何表達“如果字符串中存在子字符串,則該做什么”?

[英]How to express “if substring present in string do something” when using strstr?

我正在嘗試編寫一個非常簡單的程序,該程序需要一個字符串(氨基酸或核酸),並檢查一個子字符串出現多少次並輸出結果。

但是,我不知道如何在while if循環中聲明加1以僅在存在匹配項時計數,並在到達行尾時制動。 由於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);
 }

}

您還會為調試寫什么(因為我正在嘗試練習)?

預先感謝您的幫助,如果問題沒有明確提出,對不起。

strstr返回一個指向您要查找的字符串的出現的指針,如果不存在則返回NULL 因此,您應該循環執行直到獲得NULL ,並且每次獲得有效的指針時,都要遞增計數器,然后從其后立即開始尋找:

char* loc = NULL;
while (loc = strstr(prot_seq,desired_seq)) {
    count++;
    loc++;
}

暫無
暫無

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

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