How to Compare Strings in C

When you are dealing with any programming language, you need to do some operations or you have to code some conditions i.e. if something happens, what result it will produce etc. comparing to numbers or values is very simple process i.e. you can easily compare two integers or factorial values simply by using “==” operator, but comparing two different strings is a tricky part and beginners often do it wrong. Following step by step guide will teach you to compare two strings using examples in C language.

Instructions

  • 1

    So first thing which you have to keep in mind is that always include appropriate libraries because the entire API come from libraries. In our case here we need to include “string.h” because it contains majority of the string API we are going to use in this procedure. So include the library by typing following line at start of your code.
    • #include

  • 2

    Second step is to declare two strings. In C++ declaring strings is simple as you can only use string type to initialize a string but in C language it is slightly different because here string is declared as an array of characters so declare two strings using following lines.


    • char S1[20];


    • char S2[20];


    You can change the length of a string from 20 to any number.

  • 3

    You can either compare whole strings or you can simply decide the length of characters in a string you want to compare. To compare the two strings we will use strncmp API. To compare the above strings decide the length to compare e.g. we will compare whole strings. You can do it by using following line of code.




    int   our_result  =   strncmp(S1, S2, 20);

    You can change the third input variable as required e.g. you want to compare only first two characters then you can simply replace 20 by 2.

  • 4


    Now the return value in our_result variable will be positive, negative or 0. It will be positive if S1 is larger than S2, it will be negative is S2 > S1 and it will be zero if both are equal.


    So to make a check write following lines of code:


    if (our_result > 0)


    printf(“S1 is larger”);


    else if(our_result<0)


    printf(“S2 is larger”);


    else


    printf(“both are equal”);


    You can use these simple steps in your code and you can modify them according to your needs.



Leave a Reply

Your email address will not be published. Required fields are marked *


− seven = 0