facebook like button

06 April, 2011

program 27: comparison of two strings

The need:
     In previous post we came to know about index and accessing of elements of a string (basically an array of characters.) In the remark of previous post I told that there is a header file which deals with strings. In this program I am introducing that header file "<string.h>" to you. This program takes 2 strings as input, prints their lengths and tells whether they are equal or not.

The code: 
--------------------------------------------
#define MAX_LENGTH 50
#include<stdio.h>
#include<string.h>
int main()
{
    int i,l1,l2;              // declaration of 3 integers
    char str1[MAX_LENGTH],
str2[MAX_LENGTH];     //declaration of two character strings str1 and str2
    printf("Enter string1\n");
    gets(str1);            // getting string and storing in str1

    printf("Enter string2\n");
    gets(str2);            // getting string and storing in str2

    l1=strlen(str1);       // getting length of str1 into l1
    l2=strlen(str2);       // getting length of str2 into l2
    i=strcmp(str1,str2);   // strcmp compares strings str1 & str2
    printf("length of string %s is %d\n",str1,l1);
    printf("length of string %s is %d\n",str2,l2);
    if(i==0)
    printf("given strings are same.\n");
    else
    printf("given strings are not same.\n");
    return 0;
}

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

The approach:
     First of all run the program. Read the following explanation and try to understand the code. I hope you remember the use of #define directive(program9).
   This program takes two strings as input. This is well understood by you. Then I have used built-in function strlen() to get the length of str1 and then str2. strlen() function calculates the length of string given to it as argument and returns it to the variable left of '=' sign. So we have length of str1 and str2 in 'l1' and 'l2' respectively. Then function strcmp() is used which takes 2 strings as arguments(here str1 and str2). This returns 0 if the given strings(strings given to it as arguments) are equal else returns non-zero value. So by checking the value of I we can say whether the given strings are same or not and print the corresponding statement. This is done using if...else... statement.


Remark:
    Here in this program I have calculated the lengths of given strings directly by using built-in function strlen(). To compare strcmp has been used. But these are not only functions in <string.h>. Some most commonly used are:
strlen
strcmp
strcpy
strcat
strstr
strncmp
strncpy
strncat
For complete reference of <string.h> visit the following links:
 

No comments:

Post a Comment

feel free to ask your doubts... if any
you can post your doubts on
www.facebook.com/programsimply