我必须编写一个程序,从命令参数中获取 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
最佳答案
只需这样做:
if (inputLine[i] == subsequence[0]) {
if (inputLine[j] != subsequence[j - i]) {
您不需要库函数来比较单个字符。
关于我可以在没有指针的情况下使用 strcmp 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47358134/