Home > Mobile >  How to check if a word is a palindrome based on the length of the word entered by user? no arrays pl
How to check if a word is a palindrome based on the length of the word entered by user? no arrays pl

Time:01-11

I am wondering how to write a small java method which allows the user to enter a sentence and the program will return all of the palindromes in the sentence. BTW: a palindrome is a word that is the same front and backwards. First, I created a method to check if one word entered by the user is a palindrome. The code is shown below. Now, I must figure out when the user enters the length of what the word should be. For example: please enter a palindrome: [user enters: racecar] please enter the size of your word: [user enters 3] Here is your palindrome: cec [as you can see, the size of length of the new word is 3] I'm not particularly sure how to obtain the new palindrome. Could someone help me? Please do not use arrays!

Here is the small method I wrote which returns true if the word entered is a palindrome (this is not what my question is asking, I think that this is something I can build off of. Of course I would return a String, so I would make the return type 'void'.)

public boolean printPalindrome(String sentence, int size)
{
String reverseStr = "";
for(int i = (sentence.length()-1); i>=size; i--)
{
reverseStr  = sentence.charAt(i);
}
if(sentence.toLowerCase().equals(reverseStr.toLowerCase()))
return true;
else
return false;
} 

CodePudding user response:

This will return the first palindrome it gets and if the size is more the the actual sentece the size will change to the sentece max length and if no palindrome is found it will return an empty string

public String printPalindrome(String sentence, int size) {
    if (size < 0) return "";
    if (size > sentence.length()) size = sentence.length();
    for (int i = 0; i   size <= sentence.length(); i  ) {
        String miniStr = sentence.substring(i, i   size);
        String reverseStr = new StringBuilder(miniStr).reverse().toString();
        if (reverseStr.equals(miniStr)) return miniStr;
    }
    return "";
}

CodePudding user response:

Is this small enough?

public List<String> findPalindromes(String sentence) {
    return Arrays.stream(sentence.split(" ")).filter(s -> new StringBuilder(s).reverse().toString().equals(s)).collect(Collectors.toList());
}
  • Related