How to use strncmp() to compares N characters from s1[] s2[][] in C

2 Answers

0 votes
#include <stdio.h>
#include <string.h>

#define LEN 3

int main(void)
{
	char s1[LEN][5] = { "AB12" , "CD98" , "AB34" };
	char s2[16] = "AB00";

	for (int i = 0; i < LEN ;i++)
		if (strncmp(s1[i], s2, 2) == 0)
			printf("Found: %s\n", s1[i]);
	return 0;
}

 
/*
   
run:
   
Found: AB12
Found: AB34

*/

 



answered Jan 26, 2016 by avibootz
edited Jan 27, 2016 by avibootz
0 votes
#include <stdio.h>
#include <string.h>

int main(void)
{
	char s1[][5] = { "AB12" , "CD98" , "AB34" };


	for (int i = 0; i < sizeof(s1)/sizeof(s1[0]) ;i++)
		if (strncmp(s1[i], "AB00", 2) == 0)
			printf("Found: %s\n", s1[i]);
	return 0;
}

 
/*
   
run:
   
Found: AB12
Found: AB34

*/

 



answered Jan 26, 2016 by avibootz
edited Jan 27, 2016 by avibootz
...