How to Compare String and Checking Palindrome in C

How to Compare String and Checking Palindrome in C Language

In this article, I will discuss How to Compare String and Checking Palindrome in C Language with Examples. Please read our previous article discussing How to Reverse a String in C Language with Examples.

How to Compare String and Checking Palindrome in C Language

Now, we will see how to compare strings and check whether a string is a palindrome. First, we will discuss what is palindrome. And then. I will explain how to check whether a string is a palindrome.

How to Compare Two Strings in C?

Comparing two strings in C typically uses the strcmp() function, part of the standard C library (string.h). This function compares two strings character by character using the ASCII value of the characters. If the strings are equal, the function returns 0. If they are not equal, it returns a positive or negative value depending on the lexicographical order of the strings. First, let us look at how to compare two strings manually, and then I will show you how to use the built-in strcmp() function. Please observe the following two strings:

How to Compare String and Checking Palindrome in C Language with Examples How to Compare String and Checking Palindrome in C Language with Examples

We have taken two strings, Boxer and Boxing. So, if we look at these strings, Box is common in both. After x, they are different. We need a method to know whether two strings are the same or different. Let’s see how to compare them. We should scan one letter at a time from both strings. So, we will take ‘i’ and ‘j’ as character pointers to scan every letter in both the strings:

How to Compare String and Checking Palindrome in C Language with Examples How to Compare String and Checking Palindrome in C Language with Examples

Here, i and j are pointing at the letter B. Both are pointing to the same letter. Increment ‘i’ and ‘j’. Again, they are pointing to the same letter, o. Increment them again. Now they are pointing letter x. After that, both the above arrays have different letters after the letter x.

How to Compare String and Checking Palindrome in C Language How to Compare String and Checking Palindrome in C Language

Now, ‘i’ and ‘j’ are pointing to different letters. Now, they are not matching. So, no need to continue further. Those two strings are different if any alphabet at corresponding locations does not match. So, the answer is the above two strings are not equal.  Now, please observe the following two strings: 

How to Compare String and Checking Palindrome in C Language How to Compare String and Checking Palindrome in C Language

Now, we have taken two strings of the same set of characters. This is the case where strings are matching. We should stop the matching if we have reached ‘\0’.

So, the procedure will compare the alphabets one by one, and when will it stop? There are two situations: if a mismatch is found, it will stop, or if any of the strings is ending, it will stop. Below is the code to perform this procedure:

Program for Comparing String in C Language:
#include <stdio.h>
#include <stdlib.h>
int main ()
{
     char B[] = "Boxer";
     char C[] = "Boxing";
     int i, j;
     printf ("1st String is \"%s\"\n", B);
     printf ("2nd String is \"%s\"\n", C);

     for (i = 0, j = 0; B[i] != '\0' && C[j] != '\0'; i++, j++)
     {
          if (B[i] != C[j])
          break;
     }

     if (B[i] == C[j])
          printf ("Both Strings Are Equal\n");
     else 
          printf ("Both Strings Are Not Equal\n");
    
     return 0;
}

Inside the for loop, we should check whether the strings match. If they’re matching, we don’t have to do anything. If they do not match, we should stop the loop execution, and coming out of the loop, we should see whether they are equal.

String Comparison using Buitt-in strcmp() Function in C:

To compare two strings in C, you typically use the strcmp function provided by the C Standard Library. This function compares two strings and returns an integer based on the comparison. Here’s how you can use it.

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

int main() {
    char str1[] = "Hello";
    char str2[] = "World";
    char str3[] = "Hello";

    int result = strcmp(str1, str2);
    if (result == 0) {
        printf("'%s' and '%s' are equal.\n", str1, str2);
    } else {
        printf("'%s' and '%s' are not equal.\n", str1, str2);
    }

    result = strcmp(str1, str3);
    if (result == 0) {
        printf("'%s' and '%s' are equal.\n", str1, str3);
    } else {
        printf("'%s' and '%s' are not equal.\n", str1, str3);
    }

    return 0;
}

In this example:

  • The comparison between str1 and str2 (“Hello” and “World”) would not be equal.
  • The comparison between str1 and str3 (“Hello” and “Hello”) would be equal.
How to Check Whether a String is a Palindrome or Not?

Now, we will understand what a palindrome is and how to check whether a string is a palindrome. If you reverse a string and it remains the same, it is known as a palindrome. Please observe the following string.

How to check whether a string is a palindrome or not?

Here, I have a string madam. When we reverse this string again, it forms the same string, madam. If you reverse a string and it remains the same, it is a palindrome. For example, naman, neven, and anna are examples of palindrome strings.

Our problem is that if a string is given, we must find out whether it’s a palindrome. Now, the procedure is: First of all, we want a reverse copy of that string. So, if we have a string in an array, we must reverse-copy it into another array. Then, we have to compare two strings: the original one and the reverse copied string. So, if they are equal, then it is a palindrome. 

Program to Check whether a string is a palindrome or not in C language:
#include <stdio.h>
#include <stdlib.h>
int main ()
{
     char B[] = "anna";
     char t;
     bool palindrome = true;
     int i, j;

     printf ("String \"%s\" is ", B);

     for (j = 0; B[j] != '\0'; j++)
     {
           // no code here
     }

     j = j - 1;

     for (i = 0; i < j; i++, j--)
     {
           if (B[i] != B[j])
           {
                  palindrome = false;
            }
     }

     if (palindrome)
           printf ("palindrome");
     else
           printf ("not palindrome");

      return 0;
}
Output:

Check whether a string is a palindrome or not Code in C language

Another Example of checking a String is Palindrome in C

The following program will include additional features such as ignoring cases and non-alphabetic characters.

  • Function to Check Palindrome: This function will take a string as input and return true if it’s a palindrome and false otherwise.
  • Ignoring Case: Convert each character to the same case (either upper or lower) before comparison.
  • Ignoring Non-Alphabetic Characters: Skip non-alphabetic characters while comparing characters from both ends.
  • Loop Through the String: Compare characters from the start and end of the string, moving towards the center.

Here’s the complete program:

#include <stdio.h>
#include <stdbool.h>
#include <ctype.h>  // for tolower() function

bool isAlpha(char c) {
    return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z');
}

bool isPalindrome(char str[]) {
    int start = 0;
    int end = 0;

    // Find the length of the string
    while (str[end] != '\0') {
        end++;
    }
    end--; // Set 'end' to the last valid character of the string

    while (start < end) {
        // Skip non-alphabetic characters
        if (!isAlpha(str[start])) {
            start++;
            continue;
        }
        if (!isAlpha(str[end])) {
            end--;
            continue;
        }

        // Compare characters
        if (tolower(str[start]) != tolower(str[end])) {
            return false;
        }

        start++;
        end--;
    }

    return true;
}

int main() {
    char str[] = "A man, a plan, a canal, Panama";

    if (isPalindrome(str)) {
        printf("The string is a palindrome.\n");
    } else {
        printf("The string is not a palindrome.\n");
    }

    return 0;
}

In this example, the function isPalindrome checks if the given string is a palindrome by considering only alphabetic characters and ignoring the case. The isAlpha function checks if a character is alphabetic and tolower from ctype.h converts characters to lowercase for case-insensitive comparison. The string “A man, a plan, a canal, Panama” is a famous palindrome that reads the same forwards and backward when spaces and punctuation are ignored.

In the next article, I will discuss How to Find Duplicates in a String in C Language with Examples. In this article, I explain How to Compare Strings and Checking Palindrome in C Language with Examples. I hope you enjoy this article, “How to Compare String and Checking Palindrome in C Language with Examples.” I would like to have your feedback. Please post your feedback, questions, or comments about this article.

Leave a Reply

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