Compare Two Strings in C


Q. Write a C program to compare two strings.

#include <stdio.h>
#include <conio.h>
#include <string.h> 
 
void main()
{
    char i[50], j[50];
    clrscr();
    printf("Enter the string of i: ");
    gets(i);
    printf("Enter the string of j: ");
    gets(j);
    clrscr();
    if (strcmp(i,j) == 0)
    {
      printf("The strings are equal.");
    }
    else
    {
      printf("The strings are not equal.");
    }
    getch();
}

Q. Write an algorithm to compare two strings.

1. Start
2. Declare two character arrays `i` and `j` to store the input strings.
3. Clear the screen (optional step related to `clrscr()` in Turbo C).
4. Prompt the user: `"Enter the string of i:"`
5. Read string `i` from the user.
6. Prompt the user: `"Enter the string of j:"`
7. Read string `j` from the user.
8. Clear the screen again (optional).
9. Use the built-in function `strcmp()` to compare string `i` and string `j`.
      - If `strcmp(i, j)` returns `0`, it means the strings are equal.
      - Otherwise, the strings are not equal.
10. According to the comparison result, print:
      - `"The strings are equal."` if they are equal.
      - `"The strings are not equal."` if they differ.
11. Wait for the user to press a key before exiting (optional related to `getch()`).
12. End



OnlineTpoint is a website that is meant to offer basic knowledge, practice and learning materials. Though all the examples have been tested and verified, we cannot ensure the correctness or completeness of all the information on our website. All contents published on this website are subject to copyright and are owned by OnlineTpoint. By using this website, you agree that you have read and understood our Terms of Use, Cookie Policy and Privacy Policy.