Hello to all,
I am new to this forum. I want to extract Palindrome from a given sentence or String? I tried various method but none of them worked out. Can anyone tell me how to Extract Palindrome from a given sentence? Please help me.
Thank you.
Hello to all,
I am new to this forum. I want to extract Palindrome from a given sentence or String? I tried various method but none of them worked out. Can anyone tell me how to Extract Palindrome from a given sentence? Please help me.
Thank you.
You have to use the String.split() method to extract all the different words from the given sentence into an array and then for each word you have to check for a palindrome. Before doing this first make the string lowercase and to remove punctuation. Now try to execute following code.
Code:String[] puncChars = {".", ",", "?", "!", ...}; String input1 = "Hello sir, are you Indian ?"; input1 = input1.toLowerCase(); for (String punct : punc1Chars) input = input1.replaceAll(punct, ""); String[] words1 = input1.split();
To extract Palindrome from a given sentence you have to use replaceAll() method for removing all punctuation from given sentence. replaceAll() process will remove all punctuation from given sentence and you will able to extract Palindrome easily from given sentence. Now you have to assign the result of the replacement back to input because given string is immutable. For this purpose you have to use following code.
input1 = input1.replaceAll(punct, "");
You have to do following steps to extract Palindrome from a given sentence.
1.You have to first read the input string or sentence.
2.Now break down that sentence into words.
3.Now extract second and second last word from given sentence.
4.Now print these word in screen.
Hey following program extract Palindrome from a given sentence. I have written that program for you. Just try to understand it. I have use for loop for accessing each character from given sentence. I also use BufferedReader for saving value for temporary. Just copy this code and paste it in your project and then try to run it.
Code:import java.io.*; public class Palindrome { public static void main(String[] args) { try { int k=0,flag=0; String [] words = null; BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); System.out.println("Enter the given string"); String inputs = br.readLine(); inputs=inputs.toLowerCase(); words = inputs.split(" "); int lefts = 0; int rights = words[k].length() -1; for(k=0;k<d/2;k++) { while (lefts < rights) { if (words[k].charAt(lefts) == words[k].charAt(rights)) { flag=1; } lefts++; rights--; } } if(flags==1) { System.out.println( "palindrome words :"+wordss); } else System.out.println("there is no plaindrome"); } catch(Exception e) { System.out.println("Error"); } } }
Bookmarks