【问题标题】:How to express "if substring present in string do something" when using strstr?使用strstr时如何表达“如果字符串中存在子字符串做某事”?
【发布时间】:2015-10-17 17:27:34
【问题描述】:

我正在尝试编写一个非常简单的程序,它接受一串字符(氨基酸或核酸)并检查子字符串出现的次数并输出结果。

但是,我不知道如何在 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() 返回一个值。使用它。
  • 抱歉,完全是编程新手。所以基本上会是 if(strstr(1)){}?
  • @SiaNravoha 如果字符串是amino acid 你想计算acid 出现了多少次?这是正确的吗 ?因为不清楚你问什么。
  • 使用计数器。在 AT 的情况下:如果您有匹配项(在位置 pos),则增加计数器。另外,您知道下一个可能的匹配项(如果有)将在pos+2 或之后。 (如果没有匹配,也没有下一个匹配;-)

标签: c string bioinformatics


【解决方案1】:

strstr 返回指向您要查找的字符串出现的指针,如果不存在则返回NULL。所以你应该循环直到你得到NULL,每次你得到一个有效的指针时,递增计数器,然后从它后面​​开始查找:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-01-29
    • 2023-03-23
    • 2021-06-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-28
    • 2021-09-25
    相关资源
    最近更新 更多