How to compare two strings

Syntax

C strncmp function has the following syntax.

int strncmp(const char *str1, const char *str2, size_t count);

Example


/*from  w w w  .j a  v  a 2s .co  m*/
#include <stdio.h>
#include <string.h>

int main()
{
  char word1[20];
  char word2[20];

  printf("\n first word:\n1: ");
  scanf("%s", word1);                                 /* Read the first word    */

  printf(" second word:\n 2: ");
  scanf("%s", word2);                                 /* Read the second word   */

  /* Compare the two words */
  if(strcmp(word1,word2) == 0)
    printf("identical words");
  else
    printf("%s comes before %s", (strcmp(word1, word2) > 0) ? word2 : 
               word1, (strcmp(word1, word2) < 0) ? word2 : word1);
}

Example 2


#include <stdio.h>
#include <string.h>
#include <stdlib.h>
// w  ww.j  a  v  a  2  s  .  co  m
int main(int argc, char *argv[])
{
  if(argc!=3) {
    printf("Incorrect number of arguments.");
    exit(1);
  }

  if(!strncmp(argv[1], argv[2], 8))
    printf("The strings are the same.\n");

  return 0;
}




















Home »
  C Language »
    Language Advanced »




File
Function definition
String
Pointer
Structure
Preprocessing