|
| 1 | +/* |
| 2 | + Print the palindrome words present in the sentence and its frequency. |
| 3 | +*/ |
| 4 | + |
| 5 | + |
| 6 | +import java.util.*; |
| 7 | +class sentencePalindrome |
| 8 | +{ |
| 9 | + String str; |
| 10 | + void accept() |
| 11 | + { |
| 12 | + Scanner sc=new Scanner(System.in); |
| 13 | + System.out.println("Enter a sentence"); |
| 14 | + str=sc.nextLine(); |
| 15 | + str=str.toUpperCase(); |
| 16 | + } |
| 17 | + |
| 18 | + boolean isPalin(String s) |
| 19 | + {//checks if the word is Palindrome or not |
| 20 | + int l=s.length(); |
| 21 | + String rev=""; |
| 22 | + for(int i=l-1; i>=0; i--) |
| 23 | + { |
| 24 | + rev=rev+s.charAt(i); |
| 25 | + } |
| 26 | + if(rev.equals(s)) |
| 27 | + return true; |
| 28 | + else |
| 29 | + return false; |
| 30 | + } |
| 31 | + |
| 32 | + void main() |
| 33 | + { |
| 34 | + accept(); |
| 35 | + char ch=str.charAt(str.length()-1); |
| 36 | + if(ch=='.' || ch=='!' || ch=='?') |
| 37 | + { |
| 38 | + int freq=0; |
| 39 | + StringTokenizer st=new StringTokenizer(str," .!?"); |
| 40 | + int c=st.countTokens(); |
| 41 | + for(int i=1; i<=c; i++) |
| 42 | + { |
| 43 | + String w=st.nextToken(); |
| 44 | + boolean r=isPalin(w); |
| 45 | + if (r==true) |
| 46 | + { |
| 47 | + System.out.print(w+" "); |
| 48 | + freq++; |
| 49 | + } |
| 50 | + } |
| 51 | + System.out.println(); |
| 52 | + if(freq!=0) |
| 53 | + System.out.println("NUMBER OF PALINDROMIC WORDS ="+ freq); |
| 54 | + else |
| 55 | + System.out.println("NO PALINDROMIC WORDS"); |
| 56 | + } |
| 57 | + } |
| 58 | + else |
| 59 | + System.out.println("INVALID INPUT"); |
| 60 | + } |
| 61 | +} |
0 commit comments