Comparing the given strings using strcmp() and comparing characters of two strings using strncmp() C functions

 

Compiler: Visual C++ Express Edition 2005

Compiled on Platform: Windows 2003 Server Standard Edition

Header file: Standard

Additional library: none/default

Additional project setting: Set project to be compiled as C

Project -> your_project_name Properties -> Configuration Properties -> C/C++ -> Advanced -> Compiled As: Compiled as C Code (/TC)

Other info:

To do: Comparing the given strings using strcmp() and comparing characters of two strings using strncmp() C functions

To show: Using strcmp() to compare the strings and strncmp() to compare characters of two strings

 

 

// Using strcmp()/wcscmp()/_mbscmp() and strncmp()/wcsncmp()/_mbsncmp()

#include <stdio.h>

#include <string.h>

 

int main(void)

{

char * s1 = "Happy New Year";

char *s2 = "Happy New Year";

char *s3 = "Happy Birthday";

 

printf("Using strcmp() and strncmp()\n");

printf("----------------------------\n");

printf("s1 = %s\n", s1);

printf("s2 = %s\n", s2);

printf("s3 = %s\n", s3);

printf("\nstrcmp(s1, s2) = %2d\n", strcmp(s1, s2));

printf("strcmp(s1, s3) = %2d\n", strcmp(s1, s3));

printf("strcmp(s3, s1) = %2d\n", strcmp(s3, s2));

printf("\nstrncmp(s1, s3, 6) = %2d\n", strncmp(s1, s3, 6));

printf("strncmp(s1, s3, 7) = %2d\n", strncmp(s1, s3, 7));

printf("strncmp(s1, s1, 7) = %2d\n", strncmp(s1, s3, 7));

 

return 0;

}

 

Output example:

 

Using strcmp() and strncmp()

----------------------------

s1 = Happy New Year

s2 = Happy New Year

s3 = Happy Birthday

strcmp(s1, s2) = 0

strcmp(s1, s3) = 1

strcmp(s3, s1) = -1

strncmp(s1, s3, 6) = 0

strncmp(s1, s3, 7) = 12

strncmp(s1, s1, 7) = 12

Press any key to continue . . .

 

 

C and C++ Programming Resources | C & C++ Code Example Index