Write a code to Check if the given string is Palindrome or not

 Palindrome Check

        A palindrome is a word, phrase, number, or other sequences of characters that reads the same forward and backward (ignoring spaces, punctuation, and capitalization). For example, "madam" and "racecar" are palindromes. Below, we'll explore the solutions in C, C++, Java, and Python.

What is a Palindrome?

        A palindrome is a sequence that reads the same backward as forward. Common examples include words like "radar," "level," and "rotor."

Examples:

  • "madam"

  • "racecar"

  • "A man, a plan, a canal, Panama" (ignoring spaces and punctuation)

Solutions:

        Now let's see how to check if a given string is a palindrome in different programming languages: Java, Python, C, and C++.

1. Java

        import java.util.Scanner;

        public class PalindromeCheck {
            // Function to check if a string is a palindrome
            public static boolean isPalindrome(String str) {
                // Remove all non-alphanumeric characters and convert to lowercase
                str = str.replaceAll("[^a-zA-Z0-9]", "").toLowerCase();

                // Initialize pointers at the beginning and end of the string
                int left = 0;
                int right = str.length() - 1;

                // Check characters from both ends towards the middle
                while (left < right) {
                    if (str.charAt(left) != str.charAt(right)) {
                        return false;
                    }
                    left++;
                    right--;
                }
                return true;
            }

            public static void main(String[] args) {
                Scanner scanner = new Scanner(System.in);
                System.out.print("Enter a string: ");
                String str = scanner.nextLine();
        
                // Check and print if the string is a palindrome
                if (isPalindrome(str)) {
                    System.out.println(str + " is a palindrome.");
                } else {
                    System.out.println(str + " is not a palindrome.");
                }

                scanner.close();
            }
        }

2. Python

        # Function to check if a string is a palindrome
        def is_palindrome(str):
            # Remove all non-alphanumeric characters and convert to lowercase
            str = ''.join(filter(str.isalnum, str)).lower()

            # Check if the string reads the same forward and backward
            return str == str[::-1]

        # Input from user
        str = input("Enter a string: ")

        # Check and print if the string is a palindrome
        if is_palindrome(str):
            print(f"{str} is a palindrome.")
        else:
            print(f"{str} is not a palindrome.")

3. C++

        #include <iostream>
        #include <algorithm>
        #include <cctype>
        using namespace std;

        // Function to check if a string is a palindrome
        bool isPalindrome(string str) {
            // Remove all non-alphanumeric characters and convert to lowercase
            str.erase(remove_if(str.begin(), str.end(), [](char c) { return !isalnum(c); }), str.end());
            transform(str.begin(), str.end(), str.begin(), ::tolower);

            // Initialize pointers at the beginning and end of the string
            int left = 0;
            int right = str.length() - 1;

            // Check characters from both ends towards the middle
            while (left < right) {
                if (str[left] != str[right]) {
                    return false;
                }
                left++;
                right--;
            }
            return true;
        }

        int main() {
            string str;
            cout << "Enter a string: ";
            getline(cin, str);

            // Check and print if the string is a palindrome
            if (isPalindrome(str)) {
                cout << str << " is a palindrome." << endl;
            } else {
                cout << str << " is not a palindrome." << endl;
            }

            return 0;
        }

4. C

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

        // Function to check if a string is a palindrome
        int isPalindrome(char str[]) {
            int left = 0;
            int right = strlen(str) - 1;

            // Check characters from both ends towards the middle
            while (left < right) {
                // Skip non-alphanumeric characters
                if (!isalnum(str[left])) {
                    left++;
                } else if (!isalnum(str[right])) {
                    right--;
                } else if (tolower(str[left]) != tolower(str[right])) {
                    return 0;
                } else {
                    left++;
                    right--;
                }
            }
            return 1;
        }

        int main() {
            char str[100];
            printf("Enter a string: ");
            gets(str);

            // Check and print if the string is a palindrome
            if (isPalindrome(str)) {
                printf("%s is a palindrome.\n", str);
            } else {
                printf("%s is not a palindrome.\n", str);
            }

            return 0;
        }

Explanation of Code:

Each code version defines an isPalindrome function to determine if a string is a palindrome.

  • Remove Non-Alphanumeric Characters: Remove spaces and punctuation, and convert the string to lowercase to ensure a fair comparison.

  • Two-Pointer Technique: Compare characters from the beginning and end of the string moving towards the center.

  • Return Result: If all characters match, the string is a palindrome.


Sample Input & Output:

Input 1:

  • str = "radar"

Output: radar is a palindrome.

Input 2:

  • str = "hello"

Output: hello is not a palindrome.


Conclusion:

Checking if a string is a palindrome is a common task that helps improve understanding of string manipulation and character comparison in various programming languages.


**  Please do subscribe my blog for future updates and share with your friends, if you find this informative **

Comments

Popular Posts