eguruchela

Check for palindromes for strings that may contain whitespace


Answer:

A string is palindrome if it reads the same backwards as well as forwards. For example "Madam".

This string is a palindrome because if we try to read it backwards, it is the same as forward.

algorithm

Input a string.

Convert the string to lowercase to make the comparison case-insensitive.

Now, iterate through the string back and forth, comparing one character at a time until the middle of the string is reached. Skip the whitespace

If none of the characters match, break the loop.

import java.util.Scanner;
public class Palindrome  
{  
    public static void main(String[] args) { 
	Scanner input = new Scanner(System.in);
	System.out.print("Input a string : "); 
        String str = input.nextLine();  
        boolean flag = true;  
          
        //Converts the given string into lowercase  
        str = str.toLowerCase(); 
	int i, j;
	i = 0;
	j = str.length() - 1;
	while (i < j){
		while(str.charAt(i) == ' ') {
			i++;
		}
		while(str.charAt(j) == ' ') {
			j--;
		}
		if(str.charAt(i) == str.charAt(j)){
			i++;
			j--;
		    }
		    else {
			break;
		    }
		}
		if(i >= j){
 
            		System.out.println("Given string is palindrome");  
        	}
		else{  
            		System.out.println("Given string is not a palindrome");  
    		}  
	}
}
Output:
Input a string :
Madam
Given string is palindrome

👈       👉