【问题标题】:Comparing sub ranges of a char array in C比较 C 中 char 数组的子范围
【发布时间】:2012-12-09 23:02:54
【问题描述】:

我想使用 strcmp 将 char 数组的子范围与另一个字符串进行比较。 我通过读取文本文件然后将它们连接成更长的字符数组来制作 dna 字符数组。

char dna[10] = "ATGGATGATGA";
char STOP_CODON[3] = "TAA"; 
int TS1 = strcmp(&STOP_CODON[0]),dna[0]);
int TS2 = strcmp(&STOP_CODON[1]),dna[1]); 
int TS3 = strcmp(&STOP_CODON[2]),dna[2]);

if(T1+T2+T3) == 3 {
   int T = 1;  
} 

因此,如果它们都匹配,则 T 返回 true(1) 我想在三个字符的子范围内将 STOP_CODON 与 dna 进行比较。 我想不出一种简单的方法。在matlab中你可以这样做:

strcmp(STOP_CODON[1:3],dna[1:3])

在 C 中这样的事情可能吗?我想用它最终迭代整个 dna 数组,实际上是 60,000 个字符长

printf("%s.6\n",&dna[1]); 

printf 有这种功能,但我想用 strcmp 来做。在 C 中还有比这更有效的方法吗?

【问题讨论】:

  • strncmp(dna + offset, STOP_CODON, 3);
  • 甚至:strstr() BTW char STOP_CODON[3] = "TAA"; 将导致数组不是以 nul 结尾的。最好改用char STOP_CODON[] = "TAA";

标签: c arrays char range


【解决方案1】:

您不能对strcmp 执行此操作,它将比较字符串,直到它看到一个空 ('\0') 字符。相反,请使用memcmp(比较特定字节数)或strncmp(允许您指定要比较的最大字符数)。

// Compare up to 3 characters, stopping at the first null character.
if (strncmp(STOP_CODON, dna, 3) == 0) {
   // they match
}

// Copy exactly 3 bytes, even if they contain null characters.
if (memcmp(STOP_CODON, dna, 3) == 0) {
  // they match
}

还要注意,当字符串匹配时,这两个函数都返回 0(不是 1)。如果第一个字符串“小于”第二个字符串,它们将返回一个小于零的数字 小于,如果第二个字符串“小于”,它们将返回一个大于零的数字 大于第一个。

【讨论】:

    【解决方案2】:

    您只需通过添加指针来偏移到字符串中。

    const char* test = "This is a test.";
    printf("%s", test+5);   // prints "is a test.";
    

    然后你可以使用strncmp来限制你正在检查的子字符串的长度,它带有一个长度参数。

    【讨论】:

      猜你喜欢
      • 2020-10-07
      • 1970-01-01
      • 2012-04-27
      • 2013-02-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多