我必须制作一个程序,它从命令参数中获取DNA序列文件和DNA子序列,并在每次子序列及其发生次数时查找。我在第36和42行遇到了strcmp的麻烦。目前我拥有它的方式我通过GDB想出我正在比较字符串的地址而不是实际的字符串。但如果我删除&我收到一个错误。我不确定这是怎么回事。 TIA
String, length=5
dna.txt:
#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;
}
输入:
GGAAGTAGCAGGCCGCATGCTTGGAGGTAAAGTTCATGGTTCCCTGGCCC
预期产出:
./dnaSearch dna.txt GTA
答案 0 :(得分:1)
就这样做:
if (inputLine[i] == subsequence[0]) {
if (inputLine[j] != subsequence[j - i]) {
您不需要库函数来比较单个字符。
答案 1 :(得分:1)
您的字符串inputLine
是一个指向字符数组的指针,以字符&#39; \ 0&#39;终止。
strcmp期待&#39; \ 0&#39;终止字符串。
传递&inputLine[i]
将字符的地址传递到位置&#39; i&#39;到指针参数和字符串将被读取,直到&#39; \ 0&#39;字符。
正如评论中所建议的那样,您可以使用普通运算符来比较字符串字符:
if (inputLine[i] == subsequence[0]) {
flag = 0;
for (j = i + 1; j - i < seqLength; j++) {// loop
if (inputLine[j] != subsequence[j - i]) {
flag = 1;
break;
}
}
或者使用strncmp来比较子字符串:
if (strncmp(&inputLine[i], subsequence, seqLength) == 0) {
counter++;
}
答案 2 :(得分:1)
正如其他人所提到的,您不需要第一次调用strcmp
,因为您只检查单个字符。您可以直接比较它们:
if (inputLine[i] == subsequence[0]) {
然而,有一种必须简单的方法来做你想要的。由于您正在寻找另一个字符串中的子字符串,您可以使用strstr
函数来执行此操作:
while (fgets(inputLine, 200, inputFile) != NULL) { // loop through each line
char *sub = inputLine;
while ((sub = strstr(sub, subsequence) != NULL) {
counter++;
sub++;
}
}
strstr
函数将返回字符串内的指针以搜索找到的子字符串,如果没有找到则返回NULL。在上面的代码中,如果找到子字符串,则递增计数器,然后向上移动子字符串指针以继续搜索。