Write a program to take a String as input then display the palindrome word in one column and its position in another column.
Example:
Enter a String
My Mom brought a racecar
Mom \t 2
racecar \t 5
for(i=0;i<l;i++) {
c = s.charAt(i);
if(c != ' ') {
w=w+c;
r=r+c;
} else {
if(w.compareToIgnoreCase(r)==0)
w=""; r=""; //Use this code to search palindrome words
import java.util.*;
class App {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Enter a String: ");
String s = in.nextLine();
int l = s.length();
String w = "";
String r = "";
int position = 0;
for (int i = 0; i < l; i++) {
char c = s.charAt(i);
if (c != ' ') {
w = w + c;
} else {
position++;
for (int j = w.length() - 1; j >= 0; j--) {
c = w.charAt(j);
r = r + c;
}
if (w.compareToIgnoreCase(r) == 0 && r.length() > 1) {
System.out.println(w + "\t" + position);
}
w = "";
r = "";
}
if (i == l - 1) {
position++;
for (int j = w.length() - 1; j >= 0; j--) {
c = w.charAt(j);
r = r + c;
}
if (w.compareToIgnoreCase(r) == 0 && r.length() > 1) {
System.out.println(w + "\t" + position);
}
}
}
in.close();
}
}
Comments
Leave a comment