Overview reference

Problem

Goal

Check if the the user input reads the same forward and backward. Here for more explanation. In this solution we will be ignoring the case.

Pseudo-code

First of all, the user input string is obtained and reversed. Both the original value and reversed form are stripped of non-alphanumeric characters. That way, comparison would only be based on A-Z and a-z characters. If stripped original value is identical in content to the stripped reversed form, the user’s input is palindrome.

Solution

Reverse a string

private static String getreverse(String text) {
		
		String reverse = "";
		
		for(int i = text.length() - 1; i >= 0; i--) {
			
				char current = text.charAt(i);
				reverse += current;
		}
		
		return reverse;
	}

A simpler method may already exist, but we will be using the uncomplicated route. I will generate the reversed form by looping through the text starting from the last character to the first character.

Remove non-alphanumeric characters from string

private static String stripspaces(String text) {
		
		String stripped = text.replaceAll("[^a-zA-Z0-9]", "");
		return stripped;
		
	}

After testing the known palindrome, A man, a plan, a canal – Panama , I noticed the presence of the “–” character made a difference. Therefore removing all interfering characters seemed close to ideal. Looping through the word and generating a new string based on only alphanumberic characters in the string was an idea. This, however, would have required more conditional statements and consequently more lines of code. But that is an alternative, just so you know. This solution uses regex.

Trigger Action

public static void main(String[] args) {
		// TODO Auto-generated method stub
		System.out.println("Type in a text and press Ente");
		Scanner sc = new Scanner(System.in);
		String line  = sc.nextLine();
		String reverseline = CheckIfPalindrome.getreverse(line);
		String strippedline = CheckIfPalindrome.stripspaces(line);
		String strippedreverseline  = CheckIfPalindrome.stripspaces(reverseline);
		System.out.println("Your text is " + line);
		System.out.println("When stripped of all spaces: " + strippedline);
		System.out.println("The reverse form is " + reverseline);
		System.out.println("When stripped of all spaces: " + strippedreverseline);
		if(strippedreverseline.equalsIgnoreCase(strippedline)) {
			System.out.println("So your string is a palindrome");
		}else {
			System.out.println("You string isn't a palindrome.");
		}
	}

Run Program

C:<path>\com.learnjava\src\com\learnjava\beginner>java CheckIfPalindrome.java
Type in a text and press Ente
Madam, I'm Adam
Your text is Madam, I'm Adam
When stripped of all spaces: MadamImAdam
The reverse form is madA m'I ,madaM
When stripped of all spaces: madAmImadaM
So your string is a palindrome

Question

How would you prevent adding a “consider case” logic ?

Links