Compare Two Strings C Program

C Program To Compare Two Strings

Learn How To Compare Two Strings in C Programming Language. There are 3 different ways in which we can compare two given strings. It can be done using strcmp() function, pointers and without library function. The string comparison code also checks and compares the case of the characters within both the strings.


What is a String?

A String is represented by an Array of Characters in C Programming language. It is terminated using a Null character which is \0. In C programming, library functions for strings such as strcmp() are defined under string.h header file.

Must Read: C Program To Sort Name String in Descending Order

strcmp() function

  • Returns negative value if string 1 < string 2
  • Returns positive value if string 2 > string 1
  • Returns zero if string 1 = string 2

Example

String 1: CodingAlpha

String 2: Codingalpha

Result: String 1 and String 2 are different

You can use gets() to take string input from the user. But, it is not deprecated. You can use a modified version of scanf() method to input a multi-word string. scanf(“%s”, str1) will store only a single word in the string variable whereas scanf(“%[^\n]s”, str1) will store multi words in the string variable.


Must Read: C Program To Reversal of a String

C Program For String Comparison using strcmp() Function

Must Read: C Program To Convert String into Uppercase Characters

C Program To Compare Two Strings without using strcmp() Function

Must Read: C Program To Sort Names in Alphabetical Order

C Program To Compare Two Strings using Pointers

Must Read: C Program To Convert String into Lowercase Characters

Output

C Program To Compare Two Strings using Pointers, strcmp() function and without library function

In case you get any compilation errors or any doubts in this C Program for String Comparison, Pointers and strcmp() function, let us know about it in the Comment Section below.

Tushar Soni

I am Tushar Soni, Co - Founder of CodingAlpha. I am a computer science student from India and passionate about Web Development and Programming. Connect with me on Facebook | LinkedIn | Google Plus

5 thoughts on “Compare Two Strings C Program

  • October 2, 2016 at 2:38 pm
    Permalink

    Thanks a ton. I wanted to check comparison for case sensitive strings.

    Reply
  • October 2, 2016 at 6:43 pm
    Permalink

    I tried using gets() method for string comparison in my linux system. But, it’s giving an error.

    Reply
  • October 2, 2016 at 6:45 pm
    Permalink

    Thanks for so many methods to compare strings in C.

    Reply
  • October 2, 2016 at 8:15 pm
    Permalink

    There is one more string library function for comparing strings. It is strcmpi(). I think it checks the cases of the string as well.

    Reply
    • October 3, 2016 at 7:28 am
      Permalink

      In this case, strcmp() also checks the upper and lower cases of the strings.

      Reply

Join The Discussion