strcat() and strcmp() function in C language

We will learn strcat() and strcmp() string function here. We can concatenate two string using strcat() function. This will concatenate second string after first string. Where strcmp() function is used to compare two string. Here, we will see some program using strcat() and strcmp() function.

strcat() function in C, concatenate two string

We use strcat() string function to concatenate two string. It will concatenate second string after first string. Syntax of strcat() function is as follow.

// Syntax of strcat() function

strcat(firstString, secondString);

Now, we will see an example program using strcat() function.

// c program using strcat() string function
#include<stdio.h>
#include <string.h>
int main(){
  char firstStr[10]={'H', 'e', 'l', 'l', 'o', '\0'};
  char secondStr[10]={'W', 'o', 'r', 'l', 'd', '\0'};

  printf("First string before concatenate : %s\n",firstStr);

  strcat(firstStr,secondStr);
  printf("\nFirst string after concatenate : %s\n",firstStr);

  return 0;
}

Output of this C program :

strcat() function in C, concatenate string

strcmp() function in C, Compare string

We can compare two string using strcmp() string function. The strcmp() function returns 0 if both of the string is equal otherwise it returns positive or negative integers. Syntax of strcmp() function is as follows.

// syntax of strcmp() function in C

strcmp(firstString, secondString);

The strcmp() function will return negative integer if second string is bigger than first. On the other hand it will return a positive integer if first string is bigger than second. Now, lets see a C program to compare two string.

// program using strcmp() function in C, Compare string
#include<stdio.h>
#include <string.h>
int main(){
  char firstString[20],secondString[20];

  printf("Enter first string here : ");
  gets(firstString);
  printf("Enter second string here : ");
  gets(secondString);

  if(strcmp(firstString,secondString)==0){
      printf("\nBoth strings are equal.\n");

  }else if(strcmp(firstString,secondString) > 0){
      printf("\nFirst string is bigger.\n");

  }else{
      printf("\nSecond string is bigger.\n");
  }
 return 0;
}

Output of this compare string program

compare two string using strcmp() string function

If you have still any doubt about strcat() and strcmp() string function in C, then feel free to tell use using our discussion section.