int i,l,p=0,j; char c; String s,w="",r="";
System.out.println("Enter a String");
s = sc.nextLine(); s = s.trim()+" "; l = s.length();
for (i=0;i<l;i++) {
c = s.charAt(i);
if (c != 32)
w = w + c;
else { p++;
for (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"+p);
w = ""; r = "";
}
if (i == l-1) {
p++;
for (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"+p); }}}}
Q. Above coding will display palindrome words along with its position that is where it is present in the String. Add a statement to above coding so that it will display ''No palindrome words found" if there is not a single palindrome word present in the entered String.
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int i, l, p = 0, j, fu = 0;
char c;
String s, w = "", r = "";
System.out.println("Enter a String");
s = sc.nextLine();
s = s.trim() + " ";
l = s.length();
for (i = 0; i < l; i++) {
c = s.charAt(i);
if (c != 32)
w = w + c;
else {
p++;
for (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" + p);
fu++;
}
w = "";
r = "";
}
if (i == l - 1) {
p++;
for (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" + p);
fu++;
}
}
}
if(fu == 0){
System.out.println("No palindrome words found");
}
}
}
Comments
Leave a comment