Write a program to compare two string in c

20 Sep 2022 Balmiki Mandal 0 C Programming

Comparing two strings in C means checking whether the two strings are equal or not.

Write a c program to compare two string 

#include
void main()
{
    char s1[10],s2[10];
    int i;
    printf("Enter first string:");
    scanf("%s",s1);
    printf("Enter second String:");
    scanf("%s",s2);
    for(i=0;s1[i];i++)
    {
        if(s1[i]!=s2[i])
        break;
    }
    if(s1[i]==s2[i])
    printf("both the string are Equal\n");
    else
    printf("both the string are not equal\n");
}

Output:

Enter first string: ELECTRO4U

Enter second String: ELECTRO4U

both the string are Equal

 

Enter first string: ELECTRO4u

Enter second String:electro4u

both the string are not equal

In C, two strings are considered equal if and only if each corresponding character in the two strings is the same. The standard C library provides several functions for comparing strings, including:

  1. strcmp: This function compares two strings and returns an integer value indicating whether the first string is less than, greater than, or equal to the second string. The function compares the ASCII values of the characters in the two strings until a difference is found or the end of either string is reached.

  2. strncmp: This function is similar to strcmp, but only compares the first n characters of the two strings, where n is a specified integer.

  3. strcasecmp and strncasecmp: These functions are similar to strcmp and strncmp, but perform a case-insensitive comparison of the strings.

The return value of these functions can be used to determine whether the two strings are equal or not. If the return value is 0, the strings are equal. If the return value is negative, the first string is less than the second string. If the return value is positive, the first string is greater than the second string.

For example, the following code snippet demonstrates the use of the strcmp function to compare two strings:

 

Write a c program to compare two string using strcmp

#include <stdio.h>
#include <string.h>

int main() {
    char str1[20] = "hello";
    char str2[20] = "world";

    if (strcmp(str1, str2) == 0) {
        printf("The two strings are equal\n");
    } else {
        printf("The two strings are not equal\n");
    }

    return 0;
}

In this program, we use the strcmp function to compare the strings "hello" and "world". Since the strings are not equal, the function returns a non-zero value, and the program outputs the message "The two strings are not equal".

 

BY: Balmiki Mandal

Related Blogs

Post Comments.

Login to Post a Comment

No comments yet, Be the first to comment.