【发布时间】:2017-11-17 19:40:36
【问题描述】:
我必须编写一个程序,该程序从命令参数中获取一个 DNA 序列文件和一个 DNA 子序列,并找到每次子序列以及它出现的次数。我在第 36 行和第 42 行遇到了 strcmp 问题。目前,我通过 GDB 发现我正在比较字符串的地址而不是实际的字符串。但是如果我删除 & 我得到一个错误。我不确定解决此问题的正确方法是什么。 TIA
#include <stdio.h>
#include <string.h>
int main(int argc, char *argv[]) {
// place subsequence in string
char *subsequence = argv[2];
// get length of subsequence
int seqLength = strlen(subsequence);
// define file type and open for reading
FILE *inputFile = fopen(argv[1], "r");
// get each line using while loop
char inputLine[200]; // string variable to store each line
int i, j, lineLength, counter = 0, flag = -1;
while (fgets(inputLine, 200, inputFile) != NULL) { // loop through each line
lineLength = strlen(inputLine);
for (i = 0; i < lineLength; i++) { // loop through each char in the line
if (strcmp(&inputLine[i], &subsequence[0]) == 0) {
// if current char matches beginning of sequence loop through
// each of the remaining chars and check them against
// corresponding chars in the sequence
flag = 0;
for (j = i + 1; j - i < seqLength; j++) {
if (strcmp(&inputLine[j], &subsequence[j - i]) != 0) {
flag = 1;
break;
}
}
if (flag == 0) {
counter++;
}
}
}
}
fclose(inputFile);
printf("%s appears %d time(s)\n", subsequence, counter);
return 0;
}
dna.txt:
GGAAGTAGCAGGCCGCATGCTTGGAGGTAAAGTTCATGGTTCCCTGGCCC
输入:
./dnaSearch dna.txt GTA
预期输出:
GTA appears 2 times
【问题讨论】:
-
您是在比较字符串还是字符?对我来说看起来像字符。
-
那么你不需要
strcmp()。strcmp()比较以零结尾的字符串(字符序列),字符只是比较它们的数字。 -
顺便说一句,如果只是 char 比较,您可以使用
==每个字符。 -
>>I am comparing the address of the strings and not the actual strings不,您正在比较字符串。&string[index]将获取从索引到字符串末尾的子字符串。 -
您应该使用 strstr() 来定位子字符串,并观察您的应用程序的速度显着提高。