C Programs | IT Developer
IT Developer

C Programs



Share with a Friend

Strings in C

Compare Two Strings Without strcmp()

C Program: Compare Two Strings Without strcmp()

Method 1: Using gets() function

C

#include <stdio.h>

 

int main() {

    char str1[100], str2[100];

    int i = 0, flag = 0;

 

    // Input both strings

    printf("Enter first string: ");

    gets(str1); // unsafe, use fgets() in practice

 

    printf("Enter second string: ");

    gets(str2);

 

    // Compare each character

    while (str1[i] != '\0' || str2[i] != '\0') {

        if (str1[i] != str2[i]) {

            flag = 1;

            break;

        }

        i++;

    }

 

    // Display result

    if (flag == 0)

        printf("Strings are equal.\n");

    else

        printf("Strings are not equal.\n");

 

    return 0;

}

Example 1 :

Output

 
INPUT :
Enter first string: ITDeveloper
Enter second string: ITDeveloper

OUTPUT :
Strings are equal.

Example 2 :

Output

 
INPUT :
Enter first string: Hello
Enter second string: Hi

OUTPUT :
Strings are not equal.

Explanation

  1. Two strings str1 and str2 are entered by the user.
  2. Each character of both strings is compared one by one.
  3. If any mismatch is found, flag is set to 1 and the loop breaks.
  4. If no mismatch occurs, the strings are considered equal.

 

C Program: Compare Two Strings Without strcmp()

Method 2: Using fgets() function

C

#include <stdio.h>

 

int main() {

    char str1[100], str2[100];

    int i = 0, flag = 0;

 

    printf("Enter first string: ");

    fgets(str1, sizeof(str1), stdin);

 

    printf("Enter second string: ");

    fgets(str2, sizeof(str2), stdin);

 

    // Compare until newline or null terminator

    while (str1[i] != '\0' && str2[i] != '\0') {

        if (str1[i] != str2[i]) {

            flag = 1;

            break;

        }

        if (str1[i] == '\n' || str2[i] == '\n')

            break;

        i++;

    }

 

    if (flag == 0)

        printf("Strings are equal.\n");

    else

        printf("Strings are not equal.\n");

 

    return 0;

}

Example 1 :

Output

 
INPUT :
Enter first string: ITDeveloper
Enter second string: ITDeveloper

OUTPUT :
Strings are equal.

Example 2 :

Output

 
INPUT :
Enter first string: Hello
Enter second string: Hi

OUTPUT :
Strings are not equal.

Explanation

  1. Two strings str1 and str2 are entered by the user.
  2. Each character of both strings is compared one by one.
  3. If any mismatch is found, flag is set to 1 and the loop breaks.
  4. If no mismatch occurs, the strings are considered equal.