3

I want to compare a sub range of a char array to another string using strcmp. I made the dna char array by reading from a textfile and then concatenating them into a longer char array.

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;  
} 

So if they all match then T returns as true(1) I want to compare the STOP_CODON with dna in subranges of three chars. I cant figure a way to do this simply. In matlab you can do:

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

Is something like this possible in C? I want to use this to eventually iterate over the whole dna array which is actuality is 60,000 chars long

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

printf has this kind of functionality but I want to so this with strcmp. Is there something more efficient than this in C?

Ben Fossen
  • 997
  • 6
  • 22
  • 48

2 Answers2

6

You can't do this with strcmp, which will compare strings until it sees a null ('\0') character. Instead, use either memcmp, which compares a specific number of bytes, or strncmp, which allows you to specify the maximum number of characters to compare.

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

or

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

Note, also, that both of these functions return 0 (not 1) when the strings match. They'll return a number less than zero if the first string is “less than” the second, or a number greater than zero if the second string is “less than” the first.

Adam Liss
  • 47,594
  • 12
  • 108
  • 150
2

You simply offset into the string, by adding to the pointer.

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

Then you can limit the length of the substring you're checking by using strncmp, which take a length parameter.

Jonathon Reinhart
  • 132,704
  • 33
  • 254
  • 328