Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Palindrome Checker using StringBuilder

Im trying to create a palindrome checker. I am using a StringBuilder and I've discovered that appending spaces are kind of tricky.

EDIT: are there other ways besides using .reverse()? Thanks for the answers. :D

This code works when the word has no spaces:

public String palindrome (String anyString) {

StringBuilder sb = new StringBuilder();

for (int i = anyString.length()-1; i>=0; i--) {
        sb.append(anyString.charAt(i));
}

String string2 = sb.toString();

return string2;
}

When the word entered has a space; it returns a string that includes characters up to the first space.

E.g.:

word = "not a palindrome"
palindrome(word) = "emordnilap"

expected = "emordnilap a ton"


I have tried inserting

if (anyString.charAt(i) != ' ')
    sb.append(anyString.charAt(i));
else 
    sb.append(' ');

at the middle of the code but it doesn't work.

Thanks guys!

like image 355
user1993177 Avatar asked Mar 06 '13 14:03

user1993177


2 Answers

Use StringBuilder.reverse() method instead, it works faster (1378 line) and more correct

StringBuilder sb = new StringBuilder("not a palindrome");
System.out.println(sb.reverse());

Output:

emordnilap a ton

like image 87
bsiamionau Avatar answered Nov 02 '22 22:11

bsiamionau


public static boolean isPalindromeNaive(String s){
    StringBuilder sb = new StringBuilder(s);
    StringBuilder sbReverse = sb.reverse();
    if (s.equals(String.valueOf(sbReverse))){
        return true;
    }
    return false;
}

Doesn't seem to be what you are looking for but it's the complete method just for reference.

like image 44
Mona Jalal Avatar answered Nov 02 '22 23:11

Mona Jalal